cancelling a handler.postdelayed process

AndroidAndroid HandlerPostdelayed

Android Problem Overview


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 way to cancel the postDelayed task before the time elapses.

Android Solutions


Solution 1 - Android

I do this to post a delayed runnable:

myHandler.postDelayed(myRunnable, SPLASH_DISPLAY_LENGTH); 

And this to remove it: myHandler.removeCallbacks(myRunnable);

Solution 2 - Android

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.

Solution 3 - Android

Another way is to handle the Runnable itself:

Runnable r = new Runnable {
    public void run() {
        if (booleanCancelMember != false) {
            //do what you need
        }
    }
}

Solution 4 - Android

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

Solution 5 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRonView Question on Stackoverflow
Solution 1 - AndroidVarunView Answer on Stackoverflow
Solution 2 - AndroidManiView Answer on Stackoverflow
Solution 3 - AndroidcodeScriberView Answer on Stackoverflow
Solution 4 - AndroidStéphane PadovaniView Answer on Stackoverflow
Solution 5 - AndroidRamin FallahzadehView Answer on Stackoverflow