Handler message mechanism source code analysis

Source: Internet
Author: User

    public static final Looper myLooper() {        return (Looper)sThreadLocal.get();    }

Here is a summary of the handler execution process:


1. logoff. Prepare () method
Bind logoff to the current thread,
Create a messagequeue In The logoff Constructor

2. Create handler and write handlemessage

3. Use handler to send messages, and the final messages will be sent to the messagequeue object. In messagequeue, all messages are arranged in ascending order of the time they should be executed.

4. logoff. Loop ()
In this method, enable the dead loop, constantly extract the message to be executed from messagequeue, and execute the dispatchmessage method in the handler corresponding to the message, that is, execute the handlemessage method we override.

Create a handler object in the Child thread according to the above analysis:

New thread () {@ override public void run () {message MSG = message. obtain (); loinherit. prepare (); // If this rule is not called, an exception can't create handler inside thread that has not called logoff is thrown. prepare () handler handler2 = new handler () {public void handlemessage (Message MSG) {toast. maketext (mainactivity. this, "receiving subthread message", 0 ). show () ;};}; handler2.sendmessage (MSG); Looper. loop ();}}. start ();
Compared to creating a handler instance object in the main thread, we found that to create a handler object in the Child thread, we need to call logoff before the creation. the prepare () method is called after being created. what are the two methods for loop?

First, let's look at the system's lorule. Prepare method:

Public static final void prepare () {If (sthreadlocal. Get ()! = NULL) {Throw new runtimeexception ("only one Looper may be created per Thread");} // binds a looper object to the current thread and uses sthreadlocal as the key sthreadlocal. set (New logoff ());}
That is, when the lorule. Prepare method is called, the current thread is bound with a lorule object. Therefore, the lorule. Prepare method can only be called once, that is, a thread can only have one lorule object.

Let's take a look at the logoff constructor:

 private Looper() {        mQueue = new MessageQueue();    }
A thread can have only one loose object, so a thread can have only one messagequeue object.


Let's take a look at the handler constructor:

Public handler () {// obtain the logoff object of the current thread, mlogoff = logoff. mylooper (); If (mloexception = NULL) {Throw new runtimeexception ("can't create handler inside thread that has not called loled. prepare () ");} // obtain the reference mqueue = mloue. mqueue ;}

Let's take a look at the system's lorule. mylorule method: that is, to obtain the lorule object that stores sthreadload when the lorule. Prepare method is called, so the lorule. Prepare method must be called before the new handler method.

    public static final Looper myLooper() {        return (Looper)sThreadLocal.get();    }

That is, when a handler is created, the logoff. mylogoff () method is called to obtain the logoff object of the current thread. If logoff = NULL, an exception is thrown.

The preceding two methods show that the only loose object and messagequeue object of the current thread have been created. Next, the sendmessage is generated.

The system source code shows that the sendmessageattime (MSG, when) is called by sendemptymessage and so on );

While sendmessageattime (MSG, when); the final purpose of the method is to queue. enqueuemessage (MSG, uptimemillis); where MSG is the message object sent, and uptimemillis is systemclock. uptimemillis () + when

View the system's enqueuemessage method. This method is implemented in messagequeue. All messages are arranged in ascending order of execution.

Final Boolean enqueuemessage (Message MSG, long when) {MSG. when = when; // set the execution time to MSG. when message P = mmessages; // defines the Variable P = mmessage, at the beginning of mmessage, it points to the first message object in the column if (P = NULL | when = 0 | when <p. when) {// when the queue is empty, mmessage = MSG. next = P; mmessages = MSG; this. notify ();} else {// otherwise, the execution time of the MSG to be entered into the queue is compared with the execution time of the message in the queue, // eventually, all the messages in messagequeue are arranged in chronological order from small to large. // the messages are arranged in the order of execution. Prev = NULL; while (P! = NULL & P. when <= when) {Prev = P; P = P. next;} MSG. next = Prev. next; Prev. next = MSG; this. notify ();}}

When the message is successfully sent, The logoff. loop method is called to retrieve the message to be executed from messagequeue and execute the handlmessage method that we override.

Public static final void loop () {// obtain the logoff object of the current thread and the messagequeue object Looper me = mylooper (); messagequeue queue = me. mqueue; // enable the while (true) loop while (true) {// retrieve a message from the message queue. If the message execution time is not enough, then wait for a while for wait message MSG = queue. next (); // might block // execute the dispatchmessage method in the handler corresponding to the message, that is, execute the handlemessage method msg.tar get we override. dispatchmessage (MSG );}}}





















Handler message mechanism source code analysis

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.