removecallback and handler = null; to cancel out the handle just to keep the code clean and make sure everything will be removed.
postDelayed(new Runnable() { @Override public void run() { Intent i = new Intent(MapsActivity. this,MapsActivity. class); startActivity(i); finish(); } }, TIME_OUT); Then you can use Handler#removeCallbacksAndMessages to remove this or any callback.
Just use the removeCallbacks(Runnable r) method.
postDelayed(Runnable r, Object token, long delayMillis) Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. final void. removeCallbacks(Runnable r) Remove any pending posts of Runnable r that are in the message queue.
I do this to post a delayed runnable:
myHandler.postDelayed(myRunnable, SPLASH_DISPLAY_LENGTH);
And this to remove it: myHandler.removeCallbacks(myRunnable);
In case you do have multiple inner/anonymous runnables passed to same handler, and you want to cancel all at same event use
handler.removeCallbacksAndMessages(null);
As per documentation,
Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.
Another way is to handle the Runnable itself:
Runnable r = new Runnable {
public void run() {
if (booleanCancelMember != false) {
//do what you need
}
}
}
That's quite simple, just use the below statement and it'll cancel all the CallBacks of the Handler and remove all the pending posts of Runnable.
handler.removeCallbacksAndMessages(null);
Here is a class providing a cancel method for a delayed action
public class DelayedAction {
private Handler _handler;
private Runnable _runnable;
/**
* Constructor
* @param runnable The runnable
* @param delay The delay (in milli sec) to wait before running the runnable
*/
public DelayedAction(Runnable runnable, long delay) {
_handler = new Handler(Looper.getMainLooper());
_runnable = runnable;
_handler.postDelayed(_runnable, delay);
}
/**
* Cancel a runnable
*/
public void cancel() {
if ( _handler == null || _runnable == null ) {
return;
}
_handler.removeCallbacks(_runnable);
}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With