How logoff works
Logoff plays an important role in the message mechanism of Android,Specifically, it will constantly check whether there are new messages from MessageQueue. If there is a new message, it will immediately process and delete the message, otherwise it will be blocked.
We know that Handler requires logoff, and an error will be reported if there is no logoff thread.
In an ActivityMain threadYou can directly use Handler becauseIn the main thread of the activity, the system will use logoff. preparemainloue () to create the logoff and MessageQueue of the main thread, and use the logoff. loop () method to enable the message loop of the main thread,Therefore, you do not need to create it yourself.
HoweverChild threadTo use Handler, how can I create a logoff in a child thread?In fact, it is very easy to create a lo. prepare () for the current thread, and then enable the message loop through Looper. loop.
In a child thread, If you manually create a logoff for it,After all the tasks are completed, call the quit method to terminate the message loop. Otherwise, the sub-thread will remain in the waiting state, and the thread will terminate immediately after exiting logoff, therefore, we recommend that you terminate logoff when you do not need it.
The logoff loop method is an endless loop.The only way to jump out of the loop isThe next method of MessageQueue returns null.. When the logoff quit method is
When calling,Logoff will call the quit or quitSafely method of MessageQueue to notify the message queue to exit. When the message queue is marked as exited
The next method returns null.. That is to say, logoff is required,Otherwise, the loop method will loop infinitely.. Will the loop method call?
The next method of MessageQueue to obtain new messages,Next is a blocking operation. When there is no message, next will always be blocked., Which also causes
The loop method is always blocked. If the next method of MessageQueue returns a new message, logoff will process the message:
Msg.tar get. dispatchMessage (msg), hereMsg.tar get is the Handler object that sends this message.In this way, the Handler sends the message again
The dispatchMessage method handed to it for processing. But what's different here is,The dispatchMessage method of Handler is
The Code logic is successfully switched to the specified thread for execution..