Reputation: 16978
I just want to run a function myFunction() every X milliseconds while an external flag is true. However I've had no luck with Threads (app crashes), Timers (app crashes). Handlers/runnables are a bit better but typically I'll have something like:
Runnable rr = new Runnable() {
public void run() {
if (flag1 == true) {
myFunction();
} else {
return;
}
}
};
handler.postDelayed(rr, 1000);
But then the problem is execution will come one after another after 1000 milliseconds. I want one execution of myFunction to happen, wait 1000ms, call myFunction, wait 1000ms, call myFunction, etc, until flag1 becomes false.
I've been stuck on this for a while, so any help is much appreciated.
EDIT - more question info
The handler is defined as follows:
private Handler handler = new Handler();
And its class is a BroadcastReceiver where I'm trying to listen for flag changes based on asynchronous events from external hardware.
Upvotes: 3
Views: 7161
Reputation: 1013
This will loop and check the flag every second for the lifetime of the application.
Thread myThread = new Thread(new UpdateThread());`
myThread.start();`
public class UpdateThread implements Runnable {
@Override
public void run() {
while(true)
{
if (flag1 == true)
myFunction();
myThread.sleep(1000);
}
}
also you may want to look at a service
http://developer.android.com/reference/android/app/Service.html
Upvotes: 1