Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handler.removeCallbacksAndMessages(null) and main looper

Tags:

android

In the onDestory of a fragment, I put the code to clean up all pending runnables I started using Handler.postDelayed.

mUiHandler.removeCallbacksAndMessages(null);

I have a question here. Is it safe to call mUiHandler.removeCallbacksAndMessages(null);? What I understand is, Android does all UI operations, like UI layout, UI rendering, component lifecycles (onCreate, onPause, onResume) in main looper. Do I understand it correctly? Then, when I call mUiHandler.removeCallbacksAndMessages(null) in a fragment, will it mess up or clean up all the Android system UI operations in the message queue in main looper, since there is only one message queue in main looper.

Thanks.

like image 948
Kai Avatar asked Sep 30 '14 17:09

Kai


1 Answers

That will only remove messages and callbacks that have been posted to that specific Handler. It will not remove anything else, so yes, that's safe to do. :)

EDIT: It does share the Queue with the Looper, but it checks against the message target to make sure it came from the same Handler before removing. From MessageQueue.java:

void removeCallbacksAndMessages(Handler h, Object object) {
    if (h == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h
                && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycle();
            p = n;
        }

        ...
}
like image 153
Kevin Coppock Avatar answered Jan 17 '23 15:01

Kevin Coppock