In-depth understanding of Android asynchronous message processing mechanism,

Source: Internet
Author: User

In-depth understanding of Android asynchronous message processing mechanism,

I. Overview

 

Asynchronous Message Processing in Android consists of Message, Hndler, MessageQueue, and logoff. The relationship is shown in:

 

1. Message is a Message transmitted between threads. It can carry a small amount of information internally and is used to exchange data between different threads.

2. MessageQueue is a message queue. It is mainly used to store all the messages sent by Handler. These messages are always in the message queue and are waiting for processing. Each thread has only one MessageQueue object.

3. Handler is the processor. It is mainly used to send and process messages. Generally, handleMessage () is used to send messages. handleMessage () is called to process messages.

4. logoff is the manager of MessageQueue in each thread. After the loop () method is called, it enters an infinite loop. Every time a message is found in MessageQueue, it is taken out, and passed to handleMessage

() Method. Each thread also has only one logoff object.

 

II. Details

1. Logoff

Logoff mainly includes the prepare () and loop () methods.

  

public static final void prepare() {          if (sThreadLocal.get() != null) {              throw new RuntimeException("Only one Looper may be created per thread");          }          sThreadLocal.set(new Looper(true));  }  

SThreadLocal is a ThreadLocal object that can store variables in a thread. Logoff is stored in sThreadLocal. After this method is called, the system first checks whether there is any logoff object in the current thread. If not,

Logoff objects. If yes, an exception is thrown. It can be seen that the prepare () method cannot be called twice. This ensures that a thread has only one logoff object.

Next, let's take a look at the logoff constructor:

private Looper(boolean quitAllowed) {        mQueue = new MessageQueue(quitAllowed);        mRun = true;        mThread = Thread.currentThread();}

The MessageQueue object is created in the logoff constructor, which ensures that a thread has only one MessageQueue object.

 

Then let's 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 that of the local process,        // and keep track of what that identity token actually is.        Binder.clearCallingIdentity();        final long ident = Binder.clearCallingIdentity();        for (;;) {            Message msg = queue.next(); // might block            if (msg == null) {                // No message indicates that the message queue is quitting.                return;            }            // This must be 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.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            // 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();        }}

This method first calls the mylogoff () method to obtain the logoff object saved in sThreadLocal, and obtains the MessageQueue object corresponding to the logoff object, and then enters an infinite loop.

This loop mainly includes: retrieving a message, blocking if there is no message; Calling msg.tar get. dispatchMessage (msg); handing the message to the dispatchMessage method of the target of msg for processing.

Logoff:

1. bind with the current thread to ensure that only one logoff instance is available for one thread, and only one MessageQueue is available for one logoff instance.
  

2. The loop () method constantly retrieves messages from MessageQueue and submits them to the dispatchMessage of the target attribute of the message for processing.

 

2. Handler

Before using Handler, We Initialize an instance. For example, if it is used to update the UI thread, We Will 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;            }        };    };

  

 

3. Summary

 

1. First, logoff. prepare () saves a logoff instance in this thread, and then saves a MessageQueue object in this instance because of logoff. prepare () can be called only once in a thread, so MessageQueue only

One exists. You may also ask, so we did not display the logoff call in the Activity. prepare () and logoff. loop () method. Why can Handler be successfully created? This is because the current UI thread has called

Lorule. prepare () and lorule. loop () Methods

Initialize get. dispatchMessage (msg) method.

3. the Handler constructor will first obtain the logoff instance saved in the current thread and associate it with MessageQueue In The logoff instance.

4. The sendMessage method of Handler will assign the target value of msg to handler itself and add it to MessageQueue.

When constructing a handlerance construct in step 5, we will re-write handlemessagemessages, and parse the method finally called by msg.tar get. dispatchMessage (msg.

 

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.