Handler, Looper, MessageQueue and thread in Android

Source: Internet
Author: User

Handler, Looper, MessageQueue and thread in Android

A few days ago, and colleagues discussed the message mechanism in Android, and explored the message sending and receiving process and the relationship with the thread. Although we often use these basic things, understanding their internal principles makes it easier and more reasonable to architect the system and avoid some low-level errors.

For this part of the content, will be divided into 4 sections to describe:

1. Responsibilities and relationships

2. Message loops

3. Threads and Updates

4. A few summary

--------------------------------------------------------------------------------------------------

1) Next, we begin this part of the content, first of all to understand the respective responsibilities and the relationship between each other.

Duty

Message: Messages that contain the message ID, the message Processing object, and the processed data are queued by MessageQueue and processed by handler.

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

MessageQueue: Message Queuing, which holds messages sent by handler and executes according to FIFO rules. Of course, storing a message is not a meaningful preservation, but rather a concatenation of the message in the form of a linked list, waiting for the looper to be extracted.

Looper: The message pump continuously extracts message execution from the MessageQueue. Therefore, a MessageQueue needs a looper.

Thread: Threads that are responsible for dispatching the entire message loop, that 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 is simply a matter of aggregation, that is, Handler will refer to the specific looper and MessageQueue of the current line thread.

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

2) Next, let's take a quick look at the message's looping process:

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, It then sets the target of the message to itself (the purpose is to process the message, and the message can find the correct handler), and the message is then 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 Looper.java, we see that there is a dead loop that constantly gets the next (next method) message from the MessageQueue, and then through the target information that is carried in the message, Disposed of by the correct handler (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 call the Handlemessage method to handle this message, and that's exactly what we do in our duty Describes why you need to implement Handlemessage (Message msg) when using handler.

As for the other branch of the DispatchMessage method, I will explain it in the following sections.

So far, we see, a message through the handler send, MessageQueue the queue, Looper extraction, and again back to the arms of handler. And the circle around it just helps us turn the synchronous operation into an asynchronous operation.

3) The rest of the section, we will discuss the thread handler and how to update the UI.

In the main thread (UI thread), if the handler is created without passing in the Looper object, then the Looper object of the main thread (UI thread) will be 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 be able to 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 (Message 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 works correctly.

Therefore, handler processing messages always run in the thread that created the handler. In our message processing, there is no shortage of updates to the UI, and an incorrect thread updating the UI directly throws an exception. Therefore, you need to always be concerned about which line the handler is thread created.

How can I update the UI without 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 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 the handler. In handler, it wraps the action object passed in as a message (the callback of the message is the action) and then puts it into the message loop of the UI thread. When handler processes the message again, there is a branch (the one that is not explained) that is set for it to call the runnable run method directly. At this point, it has been routed to the UI thread, so we can update the UI with no worries.

4) Some summary

· The handler process runs on the line that creates the handler thread

· A looper corresponds to a MessageQueue

· One thread corresponds to a looper

· A looper can correspond to multiple handler

· Try to call the Post method when updating the UI when you are not sure of the current thread

Handler, Looper, MessageQueue and thread in Android

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.