Android Message delivery mechanism

Source: Internet
Author: User

Background requirements

In Android, when you encounter a child thread that needs to refresh the UI, the most common practice is handler, and of course there are other handy ways such as Android gives us the Runonuithread (runnable) method, But it all boils down to using handler to refresh the UI.

How Android Message delivery works

Simple : Handler sends (post or send) a message; MessageQueue (the team, actually a queue implemented with a single-linked list) accepts and stores the message; Looper takes a message out of MessageQueue in an infinite loop , such as MSG, and then call the Msg.target.dispatchMessage (msg) method to process the MSG. Where Msg.target is the handler to send the MSG.

SOURCE Interpretation

Handler

Handler is primarily responsible for sending messages and handling events during the Android message delivery process.

When handler sends a message, either using HANDLER.POSTXX () or using handler.sendxxx (), the final call is:

publicbooleansendMessageAtTimelong uptimeMillis) {        MessageQueue queue = mQueue;        ifnull) {            new RuntimeException(                    this" sendMessageAtTime() called with no mQueue");            Log.w("Looper", e.getMessage(), e);            returnfalse;        }        return enqueueMessage(queue, msg, uptimeMillis);    }

One of the Enqueuemessage () methods is to perform a single-linked table insert operation at the end of a queue, which is mostly done by inserting a message into the MessageQueue.

DispatchMessage (Message msg) method:

publicvoiddispatchMessage(Message msg) {        ifnull) {            handleCallback(msg);        else {            ifnull) {                if (mCallback.handleMessage(msg)) {                    return;                }            }            handleMessage(msg);        }    }

In the Looper.loop () method, the method is called to process the message MSG.

A few notes:

    1. The callback in Msg.callback is actually R in Handler.post (Runable R). Handlecallback Code:
privatestaticvoidhandleCallback(Message message) {        message.callback.run();    }

From this, it can be seen that the actual operation of Handlecallback is to call the R.run () method, that is, to invoke the thread's Run method to execute the thread's logic.

publicHandler(Callback callback){        thisfalse);    }

Where callback is an interface, namely:

publicinterface Callback {        publichandleMessage(Message msg);    }

Mcallback.handlemessage (msg) actually calls the Handlermessage method of the callback object that is passed in when the handler is constructed.
3. The last call to the Handlemessage (msg) method is actually the Handlemessage (Message msg) method that we @Override when we construct a handler.

What needs to be specifically stated are:

Handler.post (runnable R) is actually executed in the same thread as the handler.
The official notes are:
*causes the Runnable R to is added to the message queue.
* The runnable'll be run on the thread to which this handler is
* attached. *

There is a similar post (Runnable R) method in view, but the method executes in the UI thread.
The official notes are:
Causes the Runnable to is added to the message queue. The runnable'll be run on the user interface thread.

Looper

In one thread, there is only one Looper object. Looper is used in the implementation of the singleton mode.

Looper.prepare () Code:

privatestaticvoidprepare(boolean quitAllowed) {        if (sThreadLocal.getnull) {            thrownew RuntimeException("Only one Looper may be created per thread");        }        sThreadLocal.set(new Looper(quitAllowed));    }

New Looper (quitallowed) code:

privateLooper(boolean quitAllowed) {        new MessageQueue(quitAllowed);        mThread = Thread.currentThread();//当前looper所在线程    }

As can be seen here, Looper's construction method is private, indicating that the current looper is using a singleton pattern, only in the Mylooper () method to return, code:return Sthreadlocal.get ().

Summarize

Handler: Send and process message
Looper: Create a MessageQueue for a thread so that handler can be used in that thread.

Android Message delivery 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.