Handler, Looper, message analysis

Source: Internet
Author: User

As we all know, time-consuming operations should not be performed in the main thread, such as fetching data from the server and updating the interface. However, the interface update can only be performed in the main thread. In this case, the thread gets the data from the server, and then sends the data to the main thread via handler and updates the interface in the main thread. In general, we are doing this:

1 NewThread (NewRunnable () {2 @Override3      Public voidrun () {4 Looper.prepare ();5Mhandler =NewMyHandler ();6Message msg =NewMessage ();7Msg.obj = "Text";8 mhandler.sendmessage (msg);9 Looper.loop ();Ten } One}). Start ();

MyHandler inherits the handler, and the Handlemessage (Message msg) method is replicated, the code is as follows:

1 class extends handler{2  @Override3publicvoid  handlemessage (Message msg) {4 string text = (string) msg.obj; 5 mtextview.settext (text); 6 }7 }   


In the Handlemessage method, you can process the data sent from the thread and update the control (Mtextview). Know how to use, have an egg with Ah, must know its principle AH (decay!!!) )。 Then let's look at the source code.

1) To see what Looper.prepare has done? The
Prepare () method called its overloaded method and passed in the parameter true.

 1  private  static  void  Prepare (boolean   quitallowed) { 2  if  ( Sthreadlocal.get ()! = null  ) { 3  throw  new  runtimeexception (" Looper may created per thread " 4   5
       Sthreadlocal.set (new   Looper (quitallowed )); 6 } 

Sthreadlocal is Threadloacl is the object, about threadlocal, only need to know threadlocal for each thread that uses the variable to provide a separate copy of the variable, so each thread can independently change their own copy, Without affecting the replicas of other threads. The sthreadlocal here holds the Looper object. There can be at most one looper in a thread and can only be created in the Prepare method. So only one looper.prepare can be called at most once in a thread, or runtimeexception will be thrown ("single Looper may be created per thread").
Sthreadlocal.set (New Looper (quitallowed)); New has a looper and adds it into the sthreadlocal.
2) What has been done in the construction of the Looper method?

1 Private Looper (boolean2new  MessageQueue (quitallowed); 3 true ; 4 mthread = thread.currentthread (); 5 }

MessageQueue is a FIFO message queue, and the message we send through handler is made by it.

3) Send Message
Now that the MessageQueue has already been sent, it is waiting for the message to come. The message sent through the Handler.sendmessage method will eventually go into the following method:

1  Public BooleanSendmessageattime (Message msg,LongUptimemillis) {2MessageQueue queue =Mqueue;3       if(Queue = =NULL) {4RuntimeException e =NewRuntimeException (5        This+ "Sendmessageattime () called with no Mqueue");6LOG.W ("Looper", E.getmessage (), E); 7       return false;8 }9     returnenqueuemessage (Queue, MSG, uptimemillis);Ten}

Mqueue is obtained by obtaining the looper of the current thread in the constructor method. Enqueuemessage, the final implementation is to call Messagequeue.enqueuemessage to implement, is to add the message to the queue, how to implement.

1 Final BooleanEnqueuemessage (Message msg,LongWhen ) {2     if(Msg.isinuse ()) {3       Throw NewAndroidruntimeexception (msg + "This message was already in use."));4 }5     if(Msg.target = =NULL) {6       Throw NewAndroidruntimeexception ("Message must has a target."));7 }8 9     BooleanNeedwake;Ten     synchronized( This) { One     if(mquiting) { ARuntimeException e =NewRuntimeException ( -Msg.target + "Sending message to a Handler on a dead thread"); -LOG.W ("MessageQueue", E.getmessage (), E);  the       return false; - } -  -Msg.when =When ; +Message p =mmessages; -     if(p = =NULL|| When = = 0 | | When <p.when) { +       //New Head, Wake up the event queue if blocked. AMsg.next =p; atMmessages =msg; -Needwake =mblocked; -}Else { -       //Inserted within the middle of the queue. Usually we don ' t has to wake -     //Up the event queue unless there are a barrier at the head of the queue -     //The message is the earliest asynchronous message in the queue. inNeedwake = mblocked && P.target = =NULL&&msg.isasynchronous (); - Message prev; to      for (;;) { +Prev =p; -p =P.next; the       if(p = =NULL|| When <p.when) { *          Break; $ }Panax Notoginseng       if(Needwake &&p.isasynchronous ()) { -Needwake =false; the } + } AMsg.next = p;//Invariant:p = = Prev.next thePrev.next =msg; + } - } $     if(needwake) { $ Nativewake (mptr); - } -     return true; the}

The method is a bit long, choose the key. The addition of the message is actually implemented in the section of the If Else code. Message, which is the Lian table. Know this, in fact, the above key code is not difficult to understand. The current queue is empty, or when (the number of milliseconds from power on to present, plus delay) is 0, or the current message is less than the time of the previous message, it will be judged to have no message in the current queue. The code goes into the If fragment. When there is a message in the queue, go to else and add the message to the queue by adding elements to the Lian table.
OK, send a message, add the message to the queue has been completed, how the message is taken out of the queue, and handed over to handler processing it?
4) Looper.loop ()
Take the message out of the queue and give it to handler to handle it.

1     /**                                                                                                                                                       2 * Run The message queue in this thread. Be sure to call3      * {@link#quit ()} to end of the loop.4      */5      Public Static voidLoop () {6         FinalLooper me =Mylooper ();7         if(Me = =NULL) {8             Throw NewRuntimeException ("No Looper; Looper.prepare () wasn ' t called on the This thread. ");9         }Ten         FinalMessageQueue queue =Me.mqueue; One  A         //Make sure the identity of the the the the The local process, -         //And keep track of the What, identity token actually is. - binder.clearcallingidentity (); the         Final LongIdent =binder.clearcallingidentity (); -  -          for (;;) { -Message msg = Queue.next ();//might block +             if(msg = =NULL) { -                 //No message indicates that the message queue is quitting. +                 return; A             } at  -             //This must is in a local variable with case a UI event sets the logger -Printer logging =me.mlogging; -             if(Logging! =NULL) { -Logging.println (">>>>> dispatching to" + Msg.target + "" + -Msg.callback + ":" +msg.what); in             } -  to msg.target.dispatchMessage (msg); +  -             if(Logging! =NULL) { theLogging.println ("<<<<< finished to" + Msg.target + "+ msg.callback);

The amount, too, is quite long, likewise, to look at the point. Message msg = Queue.next (); this, with the toe of the head, is also to remove messages from the queue. No, look. Msg.target.dispatchMessage (msg); Msg.target, is handler.
Handler.dispatchmessage as follows:

1      Public voidDispatchMessage (Message msg) { 2         if(Msg.callback! =NULL) {3 handlecallback (msg);4}Else {5             if(Mcallback! =NULL) {6                 if(Mcallback.handlemessage (msg)) {7                     return;8                 }   9             }   Ten handlemessage (msg); One         }    A}

This, see the handlemessage that we are familiar with.
Call it

Handler, Looper, message analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.