Reputation: 33
I created a handler, to imitate timer task.
because TimerTask was acting differently on different tablets.
so I created this handler method.
in timer there was a method timerTask.cancel();
but how to stop this handler
it keeps on running even after the application is exited.
as you can see logs running even after back press.
Handler handler = new Handler();
public void recursivelycallHandler(){
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d("handler is running", "true" + System.currentTimeMillis());
recursivelycallHandler();
}
}, 100);
}
Upvotes: 3
Views: 3710
Reputation: 2023
There are 3 methods to do that ..
handler.removeCallbacks(Runnable r);
handler.removeCallbacksAndMessages(null);
handler.removeMessages(int what)
In your case first two seem feasible .. add any of the above method in ondestroy or on a listener to backpress..
Upvotes: 3
Reputation: 30855
By putting any condition
Handler handler = new Handler();
int i = 0;
Runnable myRunnable = new Runnable() {
@Override
public void run() {
Log.d("handler is running", "true" + System.currentTimeMillis());
if(i>5)
handler.removeCallback(myRunnable);
else{
i++;
handler.postDelayed(myRunnable, 100); // here is self calling
}
}
};
}
handler.postDelayed(myRunnable, 100);
Its recursive method but you can call the same Runnable object in run() instead of recursive method and remove that object when based on specific situation/condition
Upvotes: 1
Reputation: 9276
just add isFinished to your run method:
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (isFinished())
return;
Log.d("handler is running", "true" + System.currentTimeMillis());
recursivelycallHandler();
}
}, 100);
Upvotes: 0
Reputation: 23596
you can do something like this below:
public void recursivelycallHandler(){
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d("handler is running", "true" + System.currentTimeMillis());
if(YOUR_CONDITION){
recursivelycallHandler();
}
}
}, 100);
}
Hope you got my point.
feel free to comment.
Upvotes: 0
Reputation: 3893
You can store flag (boolean var) to detect if you need to call for your handler and before exit app change this flag to false and stop calling handler.
Upvotes: 0