Parsing asynchronous Message processing mechanisms

Source: Internet
Author: User

I. Overview
The Android asynchronous message processing mechanism consists of four parts, message, Handle, MessageQueue, and Looper. I'll give you a brief introduction to these four sections below.
1.Message
A message is an information that is passed between threads, and it can carry a small number of messages inside to exchange data between different threading.
2.MessageQueue
MessageQueue is a message queue that is primarily used to store all messages sent by Handler, which are kept in the message queue and waiting to be processed. There will only be one MessageQueue object in each thread.
3.Handle
Handler, as the name implies, is the meaning of the processor, which is primarily used to send and process messages. Sending a message typically uses the handler SendMessage () method, and processing the message calls the Handlemessage () method.
4.Looper
Looper is the steward of MessageQueue in each thread, and when the loop () method is called, it goes into an infinite loop, and whenever a message is found in MessageQueue, it is removed and passed to the Handlemessage () method. There will only be one Looper object in each thread.
After understanding the basic concepts of message, Handle, MessageQueue, and Looper, let's comb through the entire process of asynchronous message processing. You first need to create a handle object in the main thread and override the Handlemessage () method. Then, when UI action is required in a child thread, a message object is created and sent out through handle. The message is then added to the MessageQueue queue for processing, and Looper tries to remove the pending message from MessageQueue and finally distributes it back to the Handlemessage () method of handle. Since handle is created in the main thread, the code in the Handlemessage () method will also run in the main thread, so we can do the UI operation safely here. The flow of the entire asynchronous message processing mechanism.

This is the core idea of the entire asynchronous message processing mechanism, after a message has been called through such a process, that is, from the child thread into the main thread, from the inability to update the UI to the updatable UI.

Second, Detailed introduction
1, Looper
For Looper The main is the prepare () and loop () two methods.

 public  static  final  void   prepare () { if  (Sthreadlocal.get ()! = null  ) {  throw  new  runtimeexception ("          Looper may created per thread " new  Looper (true

Sthreadlocal is a Threadlocal object that can store variables in a thread. Looper is stored inside the sthreadlocal. Once this method is called, it is first judged that there are no Looper objects in the current thread, and if not, a Looper object is created and throws an exception if it exists. Visible, the prepare () method cannot be called two times. This guarantees that a thread has only one Looper object.
Let's take a look at the Looper constructor:

Private Looper (boolean  quitallowed) {        new  MessageQueue (quitallowed);         true ;         = thread.currentthread ();}

In the Looper constructor, the MessageQueue object is created, which also guarantees that a thread has only one MessageQueue object.
Then let's look at the Loop () method:

 Public Static voidLoop () {FinalLooper me =Mylooper (); if(Me = =NULL) {            Throw NewRuntimeException ("No Looper; Looper.prepare () wasn ' t called on the This thread. "); }        FinalMessageQueue queue =Me.mqueue; //Make sure the identity of the the the the The local process,//And keep track of the What, identity token actually is.binder.clearcallingidentity (); Final LongIdent =binder.clearcallingidentity ();  for (;;) {Message msg= Queue.next ();//might block            if(msg = =NULL) {                //No message indicates that the message queue is quitting.                return; }            //This must is in a local variable with case a UI event sets the loggerPrinter logging =me.mlogging; if(Logging! =NULL) {logging.println (">>>>> dispatching to" + Msg.target + "" +Msg.callback+ ": " +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//The identity of the thread wasn ' t corrupted.            Final LongNewident =binder.clearcallingidentity (); if(Ident! =newident) {LOG.WTF (TAG,"Thread identity changed from 0x" + long.tohexstring (Ident) + "to 0x" + Lon                        G.tohexstring (newident) + "while dispatching to" + Msg.target.getClass (). GetName () + "" + Msg.callback + "what=" +msg.what);        } msg.recycle (); }}

This method calls the Mylooper () method first, obtains the Looper object saved in the Sthreadlocal, and obtains the MessageQueue object corresponding to the Looper object, then enters the infinite loop.
This loop mainly includes: Take out a message, if no message is blocked, call Msg.target.dispatchMessage (msg), the message to MSG's target DispatchMessage method to deal with.
Looper main role:
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, constantly from MessageQueue to fetch messages, to the message of the target property of the DispatchMessage to handle.
2, Handler
before using Handler, we initialize an instance, for example, to update the UI thread, we initialize it directly at the time of declaration, or initialize the Handler instance in OnCreate

 private  Handler mhandler = new   Handler () { public  void   Handlemessage (Android.os.Message msg) { switch   (msg.what) { case   value:             break  ;  default  :  break  ;    }        }; };

Third, summary
1. First Looper.prepare () saves an 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 will only exist in one thread. You may also ask, in the activity, we do not show the call Looper.prepare () and the Looper.loop () method, why handler can be successfully created, because in the activity's startup code, The Looper.prepare () and Looper.loop () methods have been called in the current UI thread
2. Looper.loop () causes the current thread to enter an infinite loop, which reads the message from the MessageQueue instance and then callbacks the Msg.target.dispatchMessage (msg) method.
3, the handler method, will first get the Looper instance that is saved in the current thread, and is associated with MessageQueue in the Looper instance.
4, Handler SendMessage method, will give the target of MSG to handler itself, and then add MessageQueue.
5, when constructing handler instances, we will override the Handlemessage method, that is, Msg.target.dispatchMessage (msg) Final Call method

View Original Http://blog.csdn.net/applydev

Parsing asynchronous Message processing mechanisms

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.