How to cancel handler.postDelayed?

Android

Android Problem Overview


What if I have handler.postDelayed thread already under execution and I need to cancel it?

Android Solutions


Solution 1 - Android

I do this to cancel postDelays, per the Android: removeCallbacks removes any pending posts of Runnable r that are in the message queue.

handler.removeCallbacks(runnableRunner);

or use to remove all messages and callbacks

handler.removeCallbacksAndMessages(null);

Solution 2 - Android

If you don't want to keep a reference of the runnable, you could simply call:

handler.removeCallbacksAndMessages(null);

The official documentation says:

> ... If token is null, all callbacks and messages will be removed.

Solution 3 - Android

I had an instance where I needed to cancel a postDelayed while it was in the process of running, so the code above didn't work for my example. What I ended up doing was having a boolean check inside of my Runnable so when the code was executed after the given time it would either fire based on what the boolean value at the time was and that worked for me.

 public static Runnable getCountRunnable() {
    if (countRunnable == null) {
        countRunnable = new Runnable() {
            @Override
            public void run() {
                if (hasCountStopped)
                    getToast("The count has stopped");
            }
        };
    }
    return countRunnable;
}

FYI - in my activity destroy I do use code suggested by the other developers, handler.removecallback and handler = null; to cancel out the handle just to keep the code clean and make sure everything will be removed.

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
QuestionEugeneView Question on Stackoverflow
Solution 1 - AndroidJPMView Answer on Stackoverflow
Solution 2 - AndroidAbdelHadyView Answer on Stackoverflow
Solution 3 - AndroidJenniferGView Answer on Stackoverflow