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
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
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);
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;
}
}
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.