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.
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;
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With