Eugene
Eugene

Reputation: 60184

How to cancel handler.postDelayed?

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

Upvotes: 93

Views: 56058

Answers (3)

JPM
JPM

Reputation: 9296

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

Upvotes: 152

JenniferG
JenniferG

Reputation: 602

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.

Upvotes: 1

AbdelHady
AbdelHady

Reputation: 9702

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.

Upvotes: 29

Related Questions