Talk about my understanding of the message mechanism in Android Handler,looper and MessageQueue explanation

Source: Internet
Author: User

The role of handler is to send a message and handle the message sent by Message,handler is actually sent to its own object for processing, so who is sent who is handling, but this absolutely makes sense, So that we can move the processing of the message from one thread to another through handler, after a message has changed hands, the object that handles it is the same, but the thread that handles it changes and becomes the thread that creates the handler object. Instead of the thread that generated the message object (of course, this two thread may be one, but this is the second purpose of using handler), the second purpose of using handler is to have a message handle occurring at a specific time in the future, that is, the processing of deferred messages, such as Handler's postdelayed () or sendmessagedelayed () or Sendmessageattime () method.


The function of Looper is to associate a MessageQueue and poll the MessageQueue to invoke its loop () method. The creation of the Looper object needs to call its prepare () static method creation, not new. Which thread created the Looper and which thread was responsible for invoking the Looper loop () method for the polling of the message.


The role of MessageQueue is to maintain a message queue that is provided to Looper for polling, Looper contains a reference to MessageQueue, and creates a Looper object to create a corresponding MessageQueue object. This MessageQueue object is also the local message queue, because the native method was called when it was created.


Relationship between Handler and Looper and MessageQueue: a reference to a Looper object in a handler object and a reference to a MessageQueue object. Where MessageQueue is obtained through a mqueue property of its Looper object, and the Looper object is created by the thread that created the handler (the static method that created the Looper object needs to call it prepare () is created, cannot be directly new), so we can say that the MessageQueue in handler is the thread that created the handler and is actually the loop () of the Looper object created by the thread. Method to poll the MessageQueue.


The object of Looper is created by the thread that is currently creating the handler, and it is ensured that the thread is going to call the loop () method of the Looper object for the polling of the message (some native methods are called inside loop () to complete the local message polling). If you want to exit polling, you can call the Looper object's Quit () method. The UI thread (the main thread) has done all this for us, so if we create handler in the main thread, it is the main thread that automatically helps us to poll our MessageQueue, so we call the Handler object's post () in the child thread, SendMessage () to process our message in the main thread (UI thread), and to update our UI in the main thread (UI thread).


In fact post (), postdelayed (), SendMessage (), sendmessagedelayed () These four methods are essentially called sendmessageattime () this method, Just post to the Runnable object wrapped, wrapped into a Message object, and this message object callback is runnable, finally we choose the message processing method, First of all, this message object has no callback object, if any, call this callback object, and then see the entire handler object has no callback object, if any, call this callback object Handlemessage The () method processes the Message object and, if not, calls the Handlemessage method of the handler object itself to process the message, so that message processing is prioritized.


Handler,looper and MessageQueue's containment relationship
Handler contains the Looper, also contains the Looper MessageQueue;
Looper contains the MessageQueue,


So looper belongs to handler, created and used by the thread that created the handler, MessageQueue belongs to Looper, and the Handler's loop () method is called to poll by creating a thread that has been created by the Looper.


When we create the handler object in the main thread (UI thread), the handler object is associated with a Looper object, and this Looper object is not created by us, is a long time ago by the activity of Activitythread this class is created in the main function (the entry function for the entire Android application is this main function), as follows:


public static void Main (string[] args) {Samplingprofilerintegration.start ();  Closeguard defaults to True and can is quite spammy. We//Disable it here, but selectively enable it later (via/strictmode) on debug builds, but using DROPBO        x, not logs.        Closeguard.setenabled (FALSE);        Environment.initforcurrentuser ();        Set The reporter for event logging in Libcore eventlogger.setreporter (New Eventloggingreporter ());        Security.addprovider (New Androidkeystoreprovider ()); Make sure Trustedcertificatestore looks in the right place for CA certificates final File Configdir = environmen        T.getuserconfigdirectory (Userhandle.myuserid ());        Trustedcertificatestore.setdefaultuserdirectory (Configdir);        Process.setargv0 ("<pre-initialized>");        Looper.preparemainlooper ();        Activitythread thread = new Activitythread ();        Thread.attach (FALSE);        if (Smainthreadhandler = = null) {    Smainthreadhandler = Thread.gethandler (); } if (false) {Looper.mylooper (). setmessagelogging (New Logprinter (Log.debug, "Activit        Ythread "));        } looper.loop ();    throw new RuntimeException ("Main thread loop unexpectedly exited"); }


From the above code we can see that the Looper object is created by Looper.preparemainlooper (), while the polling for The loop () Start message is at the end: Looper.loop (). Through the source we can see the loop () inside is a for (;;) The dead loop of {}, this is the main thread loop for the entire application. When we developed the window application, we knew that the application was a big dead loop, called the main thread loop, and the main thread loop for the Android app was here. Now we know how our news has been polled and processed! Find the main loop, everything is solved!


Summary: Handler is responsible for sending messages and processing messages, Looper is responsible for receiving messages and polling messages, and forwarding messages to handler itself, which is handled by handler itself in different threads; MessageQueue is a container for messages. The looper contains a reference to the MessageQueue object, that is, through this container (which is actually a data structure that holds the message object in the form of a linked list), Looper to complete the polling of the message (via the loop () method).

Talk about my understanding of the message mechanism in Android Handler,looper and MessageQueue explanation

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.