I am using handler.postDelayed()
to create a waiting period before the next stage of my app takes place. During the wait period I am displaying a dialog with progress bar and cancel button.
My problem is I can't find a wa开发者_运维百科y to cancel the postDelayed task before the time elapses.
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
}
}
}
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);
}}
It worked for me when I called CancelCallBacks(this) inside the post delayed runnable by handing it via a boolean
Runnable runnable = new Runnable(){
@Override
public void run() {
Log.e("HANDLER", "run: Outside Runnable");
if (IsRecording) {
Log.e("HANDLER", "run: Runnable");
handler.postDelayed(this, 2000);
}else{
handler.removeCallbacks(this);
}
}
};
精彩评论