How to remove all callbacks from a Handler?

2022-08-31 05:35:52

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 the event, I need to remove them before finishing the Activity (somehow I called , but it still call again and again). Is there anyway to remove all callbacks from a Handler?onStopfinish()


答案 1

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.


答案 2

For any specific instance, call . Note that it uses the instance itself to determine which callbacks to unregister, so if you are creating a new instance each time a post is made, you need to make sure you have references to the exact to cancel. Example:RunnableHandler.removeCallbacks()RunnableRunnable

Handler myHandler = new Handler();
Runnable myRunnable = new Runnable() {
    public void run() {
        //Some interesting task
    }
};

You can call to post another callback to the message queue at other places in your code, and remove all pending callbacks with myHandler.postDelayed(myRunnable, x)myHandler.removeCallbacks(myRunnable)

Unfortunately, you cannot simply "clear" the entire for a , even if you make a request for the object associated with it because the methods for adding and removing items are package protected (only classes within the android.os package can call them). You may have to create a thin subclass to manage a list of s as they are posted/executed...or look at another paradigm for passing your messages between each MessageQueueHandlerMessageQueueHandlerRunnableActivity

Hope that Helps!


推荐