4

I want to make an infinite loop in android, to check if some apps are active. What is the best way to do this without using too much cpu?

Maybe a while loop or a handler or something?

Thanks,

Peter

Peter van Leeuwen
  • 938
  • 1
  • 9
  • 17

3 Answers3

20

Use a Handler:

import android.os.Handler;

// Create the Handler
private Handler handler = new Handler();

// Define the code block to be executed
private Runnable runnable = new Runnable() {
    @Override
    public void run() {
      // Insert custom code here

      // Repeat every 2 seconds
      handler.postDelayed(runnable, 2000);
    }
};

// Start the Runnable immediately
handler.post(runnable);

To remove the execution of the runnable:

handler.removeCallbacks(runnable);
Clive Seebregts
  • 2,004
  • 14
  • 18
  • 1
    To escape the error "runnable might not have been initialized" I have created an array before the `runnable` declaration `final Runnable [] runnables = new Runnable[1];` and I've replaced the line `handler.postDelayed` to this line `handler.postDelayed(runnables[0], 2000);` – Rodrigo João Bertotti Mar 10 '18 at 17:32
  • I am a beginner. My lessons says that I should avoid inner class for it may cause memory leaks. So won't this cause the same? – user9339131 Dec 31 '20 at 18:46
2

You could do something like

while(true)

Just make sure to use a break when you want to exit.

You also could do something like this:

boolean run = true;
while(run)
{
    if()//Whatever you want to cause the loop to stop.
    {
        run = false;
    }
}
duncan
  • 1,161
  • 8
  • 14
1

I would not use an infinite loop in a thread. I would use a scheduled task like this. From SO

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
     scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);

Then you can customize how frequently you want it to run by changing the TimeUnit to however frequently you need the thread to run.

Community
  • 1
  • 1
user3331142
  • 1,222
  • 1
  • 11
  • 22