DatVM DatVM - 3 months ago 33
Java Question

How to remove all callback from a Handler?

I have a handler from my sub-Activity that was called by the main Activity. This handler is used by sub-classes to postDelay some Runnables, and I can't manage them. Now, in onStop event, I need to remove them before finish the activity (somehow I called finish(), but it still call again and again). Is there anyway to remove all callbacks from a Handler?

Thanks.

Answer

In my experience calling this worked great!

handler.removeCallbacksAndMessages(null);

In the docs for removeCallbacksAndMessages it says...

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