Call flow and usage scenarios for the Post method in handler

Source: Internet
Author: User

Recently has been learning multi-threading, the role of handler is really important ah, so save this piece to see pretty understand.

New Handler ();  Mhandler.post (new  Runnable () {      @Override      publicvoid  run () {          Showcontentview (Contentview);  }  });  

Now let's take a look at how this method is executed.


First of all:

 Public Final Boolean Post (Runnable R)  {      return  sendmessagedelayed (Getpostmessage (R), 0);  }  

It repackaged the runnable again and then called the Sendmessagedelayed method.



See how it's encapsulated.

Private Final Message Getpostmessage (Runnable r) {      = message.obtain ();       = R;       return m;  }  

See, used handler know that the message is the smallest unit used to record information, which encapsulates the runnable into a message object and returns





And then:

 Public Final Boolean Long Delaymillis)  {      if (Delaymillis < 0) {          = 0;      }       return sendmessageattime (msg, systemclock.uptimemillis () + delaymillis);  }  

This is where the delaymillis was tested for effectiveness.






Followed by:

 Public BooleanSendmessageattime (Message msg,LongUptimemillis) {          BooleanSent =false; MessageQueue Queue=Mqueue; if(Queue! =NULL) {Msg.target= This; Sent=queue.enqueuemessage (msg, uptimemillis); }          Else{runtimeexception e=NewRuntimeException ( This+ "Sendmessageattime () called with no Mqueue"); LOG.W ("Looper", E.getmessage (), E); }          returnsent; }  

The handler object presses the message into the MessageQueue queue.

Looks like the method to return here, then press in the information is how to send it? This has to start with the principle of handler. There are a lot of people who have written this principle, do not elaborate
You can view this blog "Android handler threading principle detailed"






And then we go to the point of distributing the information to see how it's done.

 Public Static Final voidLoop () {Looper me=Mylooper (); MessageQueue Queue=Me.mqueue;  while(true) {Message msg= Queue.next ();//might block//if (!me.mrun) {//Break ; //}              if(msg! =NULL) {                  if(Msg.target = =NULL) {                      //No Target is a magic identifier for the quit message.                     return; }                  if(me.mlogging!=NULL) Me.mLogging.println (">>>>> dispatching to" + Msg.target + "" + Msg.callback + ":" +msg.what);                  Msg.target.dispatchMessage (msg); if(me.mlogging!=NULL) Me.mLogging.println ("<<<<< finished to" + Msg.target + "" +msg.callback);              Msg.recycle (); }          }      }  

The Looper object takes the message from the MessageQueue inside out, paying attention to the sentence msg.target.dispatchMessage (msg).
The message class defines a field target, which is the handler type, and the object that is stored is the object that created the message, which is our handler object.

And then it's called The DispatchMessage (msg) method in our handler.

 Public void DispatchMessage (Message msg) {      ifnull) {          handlecallback (msg);       Else {          ifnull) {              if  (Mcallback.handlemessage ( msg) {                  return;              }          }          Handlemessage (msg);      }  }  

See no, the beginning of our runnable passed in, and then call the Getpostmessage method to assign the runnable to massage inside the callback,
When distributing, the Handlecallback (msg) method is called if callback is not null.


Finally, execute our thread.

Private Final void handlecallback (Message message) {      message.callback.run ();  }  






---------------------------------------------------------Small Split Line----------------------------------------------------------
Significance:
When we get here, we find that it seems that this thing is going round and calling the thread's run, so what's the use of that?
If we give handler a message, then we will call our handler Handlemessage (message) method, and then we'll go back to the final deal.
, but we can use runnable to directly pass in how to manipulate the object, do not need to receive the message and then to determine what the message and then choose what to do, from the code clear point of view,
I also feel that it will be clearer and easier to understand than to judge once more.




---------------------------------------------------------Small Split Line----------------------------------------------------------
The problem that is resolved:
Please look at the first paragraph of the code, the runnable executed a setcontentview (View), where the handler is called in the Onactivityresult, that is, log off after logging back to the main page of this situation, This view contains some fragment, and then the activity inside the binding fragment is required to be active, if not handler, direct execution, The activity is still in the OnPause state during the execution of the Onactivityresult method, so the error is made when the program executes to add fragment. With handler, you can ensure that the code ends up executing in the UI thread as the activity is active.

Original link: http://blog.csdn.net/panjidong_3/article/details/7890383

Call flow and usage scenarios for the Post method in handler

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.