Looper is driven by calling the loop method to carry out a message loop: Blocking out a message from MessageQueue, and then letting handler process the message, the loop method is a dead loop method.
How do you stop the message loop? We can call the Looper quit method or the Quitsafely method, which is slightly different.
Looper's Quit method source code is as follows:
publicvoidquit() { mQueue.quit(false);}
Looper's Quitsafely method source code is as follows:
publicvoidquitSafely() { mQueue.quit(true);}
The above two methods Mqueue is MessageQueue type of object, both call the MessageQueue in the Quit method, MessageQueue the source of the Quit method is as follows:
voidQuitBooleanSafe) {if(!mquitallowed) {Throw NewIllegalStateException ("Main thread not allowed to quit."); }synchronized( This) {if(mquitting) {return; } mquitting =true;if(SAFE) {removeallfuturemessageslocked (); }Else{removeallmessageslocked (); }//We can assume mptr! = 0 because mquitting was previously false.Nativewake (MPTR); }}
By observing the above source we can find:
When we call Looper's Quit method, we actually execute the Removeallmessageslocked method in MessageQueue, which is to empty all the messages in the MessageQueue message pool. Whether it is a deferred message (a deferred message is a message that needs to be deferred by sendmessagedelayed or through a method such as postdelayed) or a non-deferred message.
When we call the Quitsafely method of Looper, we actually execute the Removeallfuturemessageslocked method in MessageQueue, which can be seen by name. This method only empties all delay messages in the MessageQueue message pool and distributes all non-deferred messages in the message pool for handler to handle, quitsafely the security of the Quit method is to distribute all non-deferred messages before emptying the message.
Whether you call the Quit method or the Quitsafely method only, Looper no longer receives the new message. That is, after calling the Looper quit or quitsafely method, the message loop is terminated, which returns false when the message is sent by handler call SendMessage or post, Indicates that the message was not successfully placed in Message Queuing MessageQueue because Message Queuing has exited.
It is important to note that Looper's Quit method exists from API Level 1, but Looper's quitsafely method is added from API level 18.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The Quit method and quitsafely method for Looper in Android