An analysis of Android handle mechanism

Source: Internet
Author: User

A Use cases for handle:

1. Create a handle instance

New handle ();

2. Sending information carrier (message)

SendMessage (msg);

3. Handling Messages

Handlemessage (Message msg) {};


Two Principle Analysis

Combined with the above handle call trilogy, we will be the clues to clarify handle, Looper, Message, MessageQueue logic and relations.

1.new Handle (): This operation will generate an Handle instance, Handle instance has three properties Mlooper, Mqueue, Mcallback, the following explains the origins of these three attributes.

1.a:
Mlooper = Looper.mylooper (); Looper's Mylooper static method is also simple, public static Looper Mylooper () {return sthreadlocal.get ();}

Sthreadlocal is a singleton object whose type is Threadlocal<looper>, and this class has a set (), Get () method, whose role is the object of the current thread, The code, then, is a clear function of returning the Looper object of the current thread. In a little more detail, where is his set method? The answer is in prepare:

private static void Prepare (Boolean quitallowed) {if (sthreadlocal.get () = null) {    throw new RuntimeException ("only One Looper may be created per thread "); } sthreadlocal.set (New Looper (quitallowed));}

It is visible from this method that only one prepare method can be called in each thread, that is, only a single Looper object in each thread.

1.b:

Mqueue = Mlooper.mqueue;
The mqueue of the Looer object is a non-static variable, namely:

Final MessageQueue Mqueue;

He also generated at the time of Looper creation, MessageQueue we briefly understood as Message Queuing, but remember that he is not equal to:queue<message>

1.c:mcallback is a callback interface, and he has only one method Handlemessage:

Public interface Callback {<span style= "White-space:pre" ></span>public boolean handlemessage (Message msg) ;}


2. SendMessage (msg):

This operation is the hub of their connection we look at the first msg generation, and then the action of sending Msg.

2.a:msg generation; In the message class, we see that there is a handle type of target, and all MSG sent to handle will set this target to the current handle, such as the SendMessage () method, which would eventually be an operation:

Msg.target = this;

2.b:sendmessage (); Regardless of whether the overloaded method eventually calls Queue.enqueuemessage (MSG, Uptimemillis), this method will be queued according to when this parameter is used. That is, sort in the message queue in 1.b.


3.handleMessage: Handling message operations in the loop method in the Looper class, recalling 1.a we know that Looper is a singleton of the current thread, that is, all the message of the current thread will be processed again. There is a dead loop in the loop method that traverses the message in Mqueue and executes the DispatchMessage (msg) Method:

Msg.target.dispatchMessage (msg);

The target of the visible MSG will handle itself.

method to return to the DispatchMessage method of the handle class again

    public void DispatchMessage (Message msg) {        if (msg.callback! = null) {            handlecallback (msg);        } else {            if ( Mcallback! = null) {                if (Mcallback.handlemessage (msg)) {                    return;                }            }            Handlemessage (msg);}        }

If the mcallback is not empty, execute the Mcallback handlemessage method, otherwise execute its own Handlemessage method.


4. Summary: Android through such a clever structure to achieve the communication between the threads, if you want to thoroughly understand, in the activity as an example, in the activity to find mainthread that we usually say the main thread, You can see clearly the creation of Looper and how to manage messages.





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.