Android Development: A brief introduction to the message mechanism

Source: Internet
Author: User
Tags prepare

A few days ago, my colleagues and I explored the message mechanism in Android to explore the process of sending and receiving messages and the relationships between them. Although we often use these basics, the understanding of their internal principles makes it easier and more reasonable to frame the system and avoid some low-level errors.

Android handler, Looper, MessageQueue and thread, for this part, will be divided into 4 sections to describe:

1. Responsibilities and relationships

2. Message loop

3. Threads and Updates

4. Summary of the points

 First, Next, we start this part of the content, to understand the respective responsibilities and the relationship between each other.

Duty

Message: messages, which contain message IDs, message processing objects, and processed data, are unified by MessageQueue, and eventually handled by handler.

Handler: Processor, responsible for message delivery and processing. When using handler, you need to implement the Handlemessage (Message msg) method to handle a particular message, such as updating the UI.

MessageQueue: Message Queuing, which is used to store messages sent by handler and executed in accordance with FIFO rules. Of course, storing the message is not the actual meaning of the save, but the message is linked to the list of ways, waiting for looper extraction.

Looper: Message pump, constantly extract messages from the MessageQueue execution. Therefore, a MessageQueue needs a looper.

Thread: threads, which are responsible for scheduling the entire message loop, which is the execution site of the message loop.

Relationship

Handler,looper and MessageQueue are simple triangular relationships. Looper and MessageQueue one by one correspond, creating a looper and creating a MessageQueue. The relationship between handler and them, however, is simply a clustering relationship in which handler references the specific looper and MessageQueue of the current line Chengri.

In this way, multiple handler can share the same looper and MessageQueue. Of course, these handler also run in the same thread.

  Second, let's take a brief look at the circular process of the message:

Generated

Message msg = Mhandler.obtainmessage ();

Msg.what = what;

Msg.sendtotarget ();

Send

MessageQueue queue = Mqueue;

if (queue!= null) {

Msg.target = this;

Sent = Queue.enqueuemessage (msg, uptimemillis);

}

In Handler.java's sendmessageattime (Message msg, long Uptimemillis) method, we see that it finds the MessageQueue it references, The target of the message is then set to itself (for the purpose of processing the messages in order to find the correct handler), and then the message is included in the queue.

Extraction

Looper me = Mylooper ();

MessageQueue queue = Me.mqueue;

while (true) {

Message msg = Queue.next (); Might block

if (msg!= null) {

if (Msg.target = = null) {

No Target is a magic identifier for the quit message.

Return

}

Msg.target.dispatchMessage (msg);

Msg.recycle ();

}

}

In the loop () function of the Looper.java, we see that there is a dead loop, constantly fetching the next (next method) message from the MessageQueue, and then using the target information carried in the messages, Referred to the correct handler treatment (DispatchMessage method).

Processing

if (msg.callback!= null) {

Handlecallback (msg);

} else {

if (mcallback!= null) {

if (Mcallback.handlemessage (msg)) {

Return

}

}

Handlemessage (msg);

}

In Handler.java's DispatchMessage (Message msg) method, one of the branches is to invoke the Handlemessage method to process this message, And that's why we need to implement Handlemessage (message msg) When we describe the use of handler in our duty department.

As for the other branch of the DispatchMessage method, I will explain it later in this section.

At this point, we see, a message through the handler sent, MessageQueue team, looper extraction, and once again back to handler embrace. The circle around it also helps us to turn the synchronization operation into an asynchronous operation.

  The rest of the section, we'll discuss the threading of handler and how to update the UI.

In the main thread (UI thread), if the Looper object is not passed in when the handler is created, then the Looper object of the main thread (UI thread) is used directly (the system has been created for us), and in other threads, if the Looper object is not passed in when the handler is created, This handler will not receive processing messages. In this case, the common practice is to:

Class Looperthread extends Thread {

Public Handler Mhandler;

public void Run () {

Looper.prepare ();

Mhandler = new Handler () {

public void Handlemessage (msg) {

Process incoming messages here

}

};

Looper.loop ();

}

}

Before creating the handler, prepare a looper (looper.prepare) for the thread, and then let the Looper run (looper.loop) and extract the message so that handler can work correctly.

Therefore, handler processing messages are always run in threads that create handler. In our message processing, there is no shortage of updates to the UI, and an incorrect thread to update the UI directly throws an exception. Therefore, you need to always care about which line the handler Chengri created.

How can I update the UI to make it no exception? The SDK tells us that there are 4 ways to access the UI thread from other threads:

· Activity.runonuithread (Runnable)

· View.post (Runnable)

· View.postdelayed (Runnable, long)

· Handler

Among them, the emphasis is on the View.post (Runnable) method. In the post (Runnable action) method, view obtains the handler of the current thread (that is, the UI thread), and then posts the action object into handler. In handler, it wraps the action object passed over into a message (the callback of messages is action) and puts it into the UI thread's messaging loop. When handler processes the message again, a branch (the one that is not explained) is set up for it, calling the runnable run method directly. At this point, it has been routed to the UI thread, so we can update the UI without any hesitation.

  Iv. Summary of the points

· The handler process runs during the creation of the handler line Chengri

· A looper corresponds to a MessageQueue

· A thread corresponds to a looper

· A looper can correspond to multiple handler

· When the current thread is not determined, try to invoke the Post method when updating the UI

Related Article

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.