Handler.removeCallbacksAndMessages (null) and main looper

In the onDestory snippet I put the code to clear all pending runnables, I started using Handler.postDelayed.

mUiHandler.removeCallbacksAndMessages(null); 

I have a question here. Is it safe to call mUiHandler.removeCallbacksAndMessages (null);? As far as I understand, Android performs all the operations of the user interface, such as the layout of the user interface, visualization of the user interface, component life cycles (onCreate, onPause, onResume) in the main looper. Do I understand this correctly? Then, when I call mUiHandler.removeCallbacksAndMessages (null) in the fragment, it will ruin or clear all the Android user interfaces in the message queue in the main looper, since there is only one message queue in the main looper.

Thanks.

+5
source share
1 answer

This will delete the messages and callbacks that were sent to this particular handler. It will not delete anything, so yes, it is safe. :)

EDIT: It shares Queue with Looper , but it checks the purpose of the message to make sure that it came from the same Handler before uninstalling. 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; } ... } 
+8
source

Source: https://habr.com/ru/post/1203731/


All Articles