Everyone knows that handler is a class that is created by Android in order to be able to update the UI on a child thread.
So why handler can update the UI in handler. This is because handler switches the update UI operation to the main thread.
Some bloggers say that handler is a way of communicating between threads, which is confined to the child thread and the main thread,
One of the key things about how a child thread transmits messages to the main thread is looper.
From the example we can tell if there is a major code now
Oncrete () {
New Thread (New Runnable () {
run{
UI action---This is going to be an error, so we add handler.
Not before, now add Looper
Looper.prepare ();
New Handler () {
Handlermessage () {
Perform UI Actions---
If this is still an error because the child thread is not looper, will report no looper that error message (from the source can see added looper detection) then we add Looper
}
}
Looper.loop ();
}
}). Start;
}
After adding looper from the above code, the report should perform UI operations in the main thread.
So why, the reason is that this looper is not the main thread of the Looper
One solution is to change the Looper.prepare () to Looper.getmainlooper ();
or new Handler (Looper.getmainlooper);
So you can update the UI without an error,
So looper is how to switch the update UI to the main thread
We can see from the source that when we new Handler (Looper.getmainlooper ()) There are
Handler (Looper loopercallback callbackasync) {= looper= looper.mqueue= callback= Async}
So this time handler has got the main thread of the Looper;
Then we see in the Looper loop ();
{Msg.target.dispatchMessage (msg)} {(Tracetag! =) {Trace. ( Tracetag)}}
Will call Msg.target this msg.target is here to get
Looper me = () (Me = =) {runtimeexception ()}messagequeue queue = Me.mqueue
() {Message msg = Queue.next () (msg = =) {}
Inside the Loop () method, Looper will begin to process the information in an infinite loop.
The order is the following such
1: When instantiating activity, create activitythread (main thread) and then create looper inside Main () and looper the main thread by Mthreadlocal set method.
Then call Looper.loop (), which will open the infinite loop
2:looper.getmainlooper will call the Get method at this time to get the main thread of the Looper and the inside of the saved MessageQueue
Then handler call post is actually inserting a message on the MessageQueue of the main thread
Then the loop method inside is detected, this time has been switched to the main process.
See the source code comparison can clear the entire process
Self-summarization of Android message Machine--handler