How to remove a runnable from a handler object added by postDelayed? How to remove a runnable from a handler object added by postDelayed? android android

How to remove a runnable from a handler object added by postDelayed?


Cristian's answer is correct, but as opposed to what is stated in the answer's comments, you actually can remove callbacks for anonymous Runnables by calling removeCallbacksAndMessages(null);

As stated here:

Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.


This is a late answer, but here's a different method for when you only want to remove a specific category of runnables from the handler (i.e. in OP's case, just remove the close animation, leaving other runnables in the queue):

    int firstToken = 5;    int secondToken = 6;    //r1 to r4 are all different instances or implementations of Runnable.      mHandler.postAtTime(r1, firstToken, 0);    mHandler.postAtTime(r2, firstToken, 0);    mHandler.postAtTime(r3, secondToken, 0);    mHandler.removeCallbacksAndMessages(firstToken);    mHandler.postAtTime(r4, firstToken, 0);

The above code will execute "r3" and then "r4" only. This lets you remove a specific category of runnables defined by your token, without needing to hold any references to the runnables themselves.

Note: the source code compares tokens using the "==" operand only (it does not call .equals()), so best to use ints/Integers instead of strings for the token.