I. Overview
Handler, Looper, and messages are all related to the Android asynchronous message processing thread. So what is called an asynchronous message processing thread?
After the asynchronous message processing thread starts, it enters an infinite loop body, takes one message out of its internal message queue, and then recalls the corresponding message handler function, and then continues the loop after executing a message. If the message queue is empty, the thread blocks the wait.
Say this pile, then and handler, Looper, message have what relation? In fact, Looper is responsible for creating a MessageQueue, and then entering an infinite loop body to continuously read messages from the MessageQueue, and the creator of the message is one or more handler.
Second, source analysis
1, Looper
for Looper, the main prepare () and loop () two methods.
First look at the prepare () method
public static final void prepare () {
if (sthreadlocal.get ()!= null) {
throw new runtimeexception (' Only one looper May is created per thread ");
}
Sthreadlocal.set (New Looper (true));
Sthreadlocal is a Threadlocal object that can store variables in one thread. As you can see, in line 5th, a Looper instance is placed in the threadlocal, and 2-4 rows determine whether sthreadlocal is null or not, or throw an exception. This also explains that the Looper.prepare () method cannot be invoked two times, and also guarantees that there is only one looper instance in a thread ~ believe some buddies must have encountered this error.
Here's how Looper is constructed:
Private Looper (Boolean quitallowed) {
mqueue = new MessageQueue (quitallowed);
Mrun = true;
Mthread = Thread.CurrentThread ();
}
In the constructor method, a MessageQueue (message queue) is created.
Then we look at the loop () method:
public static void Loop () {final Looper me = Mylooper (); if (me = = null) {throw new RuntimeException ("No looper;
Looper.prepare () wasn ' t called on this thread. ");
Final MessageQueue queue = Me.mqueue; Make sure the identity of this thread is the local process,//and keep track of what that identity token AC
Tually is.
Binder.clearcallingidentity ();
Final Long ident = Binder.clearcallingidentity (); for (;;) {Message msg = Queue.next ();//might blocks if (msg = null) {//No message indicates this message Queu
E is quitting.
Return
}//This must is in a local variable, in case a UI event sets the logger Printer logging = me.mlogging; if (logging!= null) {logging.println (">>>>> dispatching to" + Msg.target + "" + Msg.callbac
K + ":" + msg.what);
Msg.target.dispatchMessage (msg); if (logging!= null) {logging.println ("<<<<< FinisHed to "+ Msg.target +" "+ msg.callback);
}//Make sure that during the course of dispatching the//identity of the thread wasn ' t corrupted.
Final Long newident = Binder.clearcallingidentity ();
if (ident!= newident) {log.wtf (TAG, "Thread identity changed from 0x" + long.tohexstring (Ident) + "to 0x" + long.tohexstring (newident) + "while dispatching to" + Msg.target.getClass (). GetName () + "" + MSG.
Callback + "what=" + msg.what);
} msg.recycle ();
}
}
Line 2nd:
public static Looper Mylooper () {return
sthreadlocal.get ();
}
method returns the Looper instance of the Sthreadlocal store directly, and if me is null throws an exception, meaning that the Looper method must run after the Prepare method.
Line 6th: Get the Mqueue in the Looper instance (Message Queuing)
13 to 45 lines: it goes into what we call an infinite loop.
Line 14: Remove a message and block if there is no message.
Line 27: Use the call Msg.target.dispatchMessage (msg), and give the message to the target DispatchMessage method of MSG to process it. What is the target of MSG? is actually the handler object, the following will be analyzed.
Line 44: Frees the resources that the message occupies.
Looper main function:
(1) bound to the current thread to ensure that a thread will have only one looper instance, while a Looper instance has only one MessageQueue.
(2) Loop () method, continuously from MessageQueue to fetch messages, to the target attribute of the message dispatchmessage to deal with.
Well, our asynchronous message processing thread already has a message queue (MessageQueue), as well as a buddy who takes out messages in an infinite loop body, and now it's the object that sent the message, so: handler.
2, Handler
Before using handler, we all initialize an instance, such as to update the UI thread, we initialize it directly when we declare it, or initialize the handler instance in OnCreate. So we first look at how the handler is constructed, and how it is associated with MessageQueue, and how messages sent in the child thread (the general sending message is in a non-UI thread) are sent to the MessageQueue.
Public Handler () {This
(null, FALSE);
}
Public Handler (Callback Callback, Boolean async) {
if (find_potential_leaks) {
final class<? extends handler& Gt Klass = GetClass ();
if ((Klass.isanonymousclass () | | klass.ismemberclass () | | klass.islocalclass ()) &&
(Klass.getmodifiers () & modifier.static) = = 0) {
log.w (TAG, "the following Handler class should be STATIC or leaks might:" +
Klass.getcanonicalname ());
}
Mlooper = Looper.mylooper ();
if (Mlooper = = null) {
throw new RuntimeException (
"Can" t create handler inside thread that is has not called Loope R.prepare () ");
}
Mqueue = Mlooper.mqueue;
Mcallback = callback;
masynchronous = async;
}
Line 14: The Looper instance saved by the current thread is obtained by Looper.mylooper (), and then the MessageQueue (Message queue) saved in the Looper instance is obtained in row 19. This ensures that the handler instance is associated with MessageQueue in our Looper instance.
Handler Common methods:
(1) post (Runnable)
(2) Postattime (Runnable,long)
(3) postdelayed (Runnable long)
(4) sendemptymessage (int)
(5) SendMessage (message)
(6) Sendmessageattime (Message,long)
(7) sendmessagedelayed (Message,long)
The above Post class method allows you to arrange a runnable object into the main thread queue, and the SendMessage class method allows you to arrange a message object with data to the queue and wait for the update.
General running Logic:
Click button---> Start a new thread to process the data----> data processing, through handler return-----> Handler to receive the returned data, UI updates, and other processing.
Then look at our most common sendmessage methods.
Public Final Boolean SendMessage (Message msg)
{return
sendmessagedelayed (msg, 0);
}
Public final Boolean sendemptymessagedelayed (int what, long Delaymillis) {
msg = Message.obtain ();
Msg.what = what;
Return sendmessagedelayed (msg, delaymillis);
Public Final Boolean sendmessagedelayed (Message msg, long Delaymillis)
{
if (Delaymillis < 0) {
Delaymillis = 0;
}
Return Sendmessageattime (MSG, systemclock.uptimemillis () + delaymillis);
public boolean sendmessageattime (msg, long Uptimemillis) {
MessageQueue queue = mqueue;
if (queue = = null) {
runtimeexception e = new RuntimeException (This
+ sendmessageattime () called with no Mque UE ");
LOG.W ("Looper", E.getmessage (), e);
return false;
}
return Enqueuemessage (Queue, MSG, uptimemillis);
The reverse is the last call to Sendmessageattime, this method has a direct fetch MessageQueue and then call the Enqueuemessage method, we will look at this method:
Private Boolean enqueuemessage (MessageQueue queue, MSG, long Uptimemillis) {
msg.target = this;
if (masynchronous) {
msg.setasynchronous (true);
}
Return Queue.enqueuemessage (msg, uptimemillis);
Meg.target is first assigned to this in Enqueuemessage, "If you remember that the loop method of Looper will take each msg out and give it to Msg,target.dispatchmessage (msg) to process the message." That is, the current handler as the target attribute of MSG. The Enqueuemessage method of the queue will eventually be invoked, meaning that the message sent by handler will eventually be saved to the message queue.
It is now clear that Looper will invoke the prepare () and loop () methods to hold a Looper instance in the currently executing thread, which saves a MessageQueue object, and then the current thread goes into an infinite loop, Constantly reading handler messages from MessageQueue. And then callback the Dispathmessage method in the handler that created the message, let's take a quick look at this method:
public void DispatchMessage (message msg) {
if (msg.callback!= null) {
handlecallback (msg);
} else {
if (mcallback!= null) {
if (Mcallback.handlemessage (msg)) {return
;
}
}
Handlemessage (msg);
}
As you can see, line 10th, which calls the Handlemessage method, let's look at this method:
/**
* Subclasses must implement this to receive messages.
*
/public void Handlemessage (message msg) {
}
You can see that this is an empty method, why, because the final callback of the message is controlled by us, we create the handler as a replication Handlemessage method, and then message processing according to Msg.what.
For example:
Private Handler Mhandler = new Handler ()
{public
void Handlemessage (android.os.Message msg)
{
switch (msg.what)
{Case
value: Break
;
Default: Break;}};
Now that the process has been explained, let's start by summarizing
(1) First looper.prepare () saves a looper instance in this thread, and then holds a MessageQueue object in the instance, because Looper.prepare () can only be called once in a thread, So MessageQueue can only exist in one thread.
(2) Looper.loop () allows the current thread to enter an infinite loop, misconduct reads the message from the MessageQueue instance, and then recalls the Msg.target.dispatchMessage (msg) method.
(3) The construction method of handler will first get the Looper instance saved in the current thread, and then associate with MessageQueue in Looper instance.
(4) The SendMessage method of handler will assign the target of MSG to handler itself and then join MessageQueue.
(5) When constructing a handler instance, we rewrite the Handlemessage method, which is the method that Msg.target.dispatchMessage (msg) ultimately invokes.
Well, summing it up, you might also ask, so in the activity, we don't show the call Looper.prepare () and Looper.loop () method, why handler can be created successfully, because in the activity's startup code, The Looper.prepare () and Looper.loop () methods have already been invoked on the current UI thread.
3, Handler Post
today, someone asked me, what do you mean, Handler's post method creates a thread that is related to a UI thread?
In fact, this is one of the reasons for this blog, we need to explain, sometimes for convenience, we will directly write the following code:
Mhandler.post (New Runnable ()
{
@Override public
Void Run ()
{
log.e ("TAG"), Thread.CurrentThread (). GetName ());
Mtxt.settext ("Yoxi");
}
);
Then the Run method can write the update UI code, in fact this runnable did not create any thread, but sent a message, look at the following source:
Public Final Boolean post (Runnable R)
{return
sendmessagedelayed (Getpostmessage (R), 0);
}
private static Message Getpostmessage (Runnable r) {message
m = Message.obtain ();
M.callback = R;
return m;
}
As you can see, in the Getpostmessage, you get a message object and then assign the Runable object we created as the callback property to this one.
Note: A message object can be created, new, or message.obtain () can be used, but the obtain method is more recommended because the message is internally maintained with a message pool used for message reuse. Avoid using new to reallocate memory.
Public Final Boolean sendmessagedelayed (Message msg, long Delaymillis)
{
if (Delaymillis < 0) {
Delaymillis = 0;
}
Return Sendmessageattime (MSG, systemclock.uptimemillis () + delaymillis);
public boolean sendmessageattime (msg, long Uptimemillis) {
MessageQueue queue = mqueue;
if (queue = = null) {
runtimeexception e = new RuntimeException (This
+ sendmessageattime () called with no Mque UE ");
LOG.W ("Looper", E.getmessage (), e);
return false;
}
return Enqueuemessage (Queue, MSG, uptimemillis);
Finally, like Handler.sendmessage, the sendmessageattime is invoked, then the Enqueuemessage method is invoked, the Msg.target is assigned to handler, and the Messagqueue is eventually added.
As you can see, the callback and target of MSG here have a value, so which is the execution?
In fact, the above has been affixed to the code, is the DispatchMessage method:
public void DispatchMessage (message msg) {
if (msg.callback!= null) {
handlecallback (msg);
} else {
if ( Mcallback!= null) {
if (Mcallback.handlemessage (msg)) {return
;
}
}
Handlemessage (msg);
Line 2nd, if not NULL, executes the callback callback, which is our Runnable object.
Well, about Looper, Handler, message These three relationships have been described very clearly.
Finally, a diagram:
Hope that the picture can better help everyone's memory ~ ~
Third, to supplement
in fact, handler not only can update the UI, you can create a handler in a child thread, and then use this handler instance to send a message in any other thread, and the final processing of the message will run in the thread where you created the handler instance.
eg
New Thread ()
{
private Handler Handler;
public void Run ()
{
looper.prepare ();
Handler = new Handler ()
{public
void Handlemessage (android.os.Message msg)
{
log.e ("TAG") Thread.CurrentThread (). GetName ());}
;
}
Android not only provides us with the asynchronous message processing mechanism for better UI updates, but also provides us with the asynchronous message processing mechanism code reference ~ ~ Not only to know the principle, it is best to use this design to other non-Android projects ~ ~