Deep understanding of the Android asynchronous message processing mechanism

Source: Internet
Author: User

One. Overview

Asynchronous message processing in Android consists of four parts, message, Hndler, MessageQueue, and Looper. The relationship is as follows:

 

1. The message is a thread passed between threads, which can carry a small amount of information inside to exchange data between different threading.

2. MessageQueue is a message queue, which is primarily used to store all messages sent by Handler, and this part of the message will remain in the message queue waiting to be processed. There will only be one MessageQueue object in each thread.

3. Handler is a processor that 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 is the steward of MessageQueue in each thread, and when the loop () method is called, it enters an infinite loop, and then 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.

Two. Detailed Introduction

1, Looper

For Looper The main is the prepare () and loop () two methods.

  

 Public Static Final void prepare () {          ifnull) {              thrownew runtimeexception ("Looper may created per thread");          }          Sthreadlocal.set (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 will first determine if there are any Looper objects in the current thread, and if not, create a

An Looper object that 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.

The 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 functions:

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 deal with.

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 New Handler ()    {        publicvoid  handlemessage (android.os.Message msg)        {            switch  (msg.what)            {            case  value:                                break;             default :                  Break ;            }        };    };

  

Three. 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 in one thread will only

There is one. 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, is already called in the current UI thread

The Looper.prepare () and Looper.loop () methods

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 override the Handlemessage method, which is the method that Msg.target.dispatchMessage (msg) eventually calls.

Deep understanding of the Android asynchronous message processing mechanism

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.