"Reprint" Summary of message mechanism issues that each Android developer must know

Source: Internet
Author: User

Android's message mechanism is almost a must-ask topic, of course, not because of the interview, but to learn, more importantly, it is essential in the development of Android, occupies a pivotal position, so it is necessary to understand it. Here's the basic thing to say.

Looper

Role:

    • Associate Thread
    • Loop out messages
1. Can looper be instantiated directly?

The Looper construction method is private, which does two things

    • Create a MessageQueue
    • Get the thread that corresponds to it
Looper(boolean quitallowed) {    new MessageQueue (quitallowed); mthread = Thread.CurrentThread ();} 
2. Can one thread correspond to multiple lopper?

No, a thread corresponds to a Looper object, and threadlocal guarantees that a thread has only one looper corresponding to it and throws a run-time exception if it is called multiple times Looper.prepare() .

Prepare (if (sthreadlocal).  New RuntimeException ("Only one Looper could becreated per thread");} sthreadlocal. Set (new Looper (quitallowed));}    
3, Looper is infinite loop, will block?

Yes, when a loop is turned on, it is a dead loop, the message is removed from the MessageQueue, the message is processed, but it is possible to exit and exit the loop after no message.

  PublicStaticvoidloop () {final Looper me = MyLooper (); if (Me = null) {throw new runtimeexception ( "No Looper; Looper.prepare () wasn ' t called on this thread. "); final MessageQueue queue = Me.mqueue; //slightly for (;;) {Message msg = Queue.next (); //might block if (msg = = null) { Span class= "Hljs-comment" >//when there is no message, exit //no message indicates that the message queue is quit Ting. return;} //slightly msg.target.dispatchMessage (msg);        
4. Can I call Looper.preparemainlooper again?

No, Looper.preparemainlooper is finally called prepare (), the same as 2.

Preparemainlooper() {Prepare (new IllegalStateException ("The main Looper has already been prepared.")} SMa Inlooper = Mylooper (); }}
5. When was Mainlooper created?

Mainlooper is created when the activity creation activitythread (not a thread) is started, so it cannot be created more than once.

public static void main(string[] args) { //slightly process.setargv0 ("<pre-initialized>"); Looper.preparemainlooper (); //Slightly activitythread thread = new Activitythread (); Thread.attach (false); //Minor if (Smainthreadhandler = = null) {Smainthreadhandler = Thread.gethandler ();} //slightly looper.loop (); throw New RuntimeException ("Main thread loop unexpectedly exited");}}      
Handler

Role:

    • Send Message to MessageQueue
    • Processing messages
1. How does handler relate to Looper and MessageQueue?

We know that a looper corresponds to a thread, and a looper contains a MessageQueue. When we create the handler, we remove the corresponding looper from the current thread, allowing the MessageQueue to be removed from the looper.

1. Automatic acquisitionPublicHandler (Callback Callback, BooleanAsync) {//slightly mlooper = Looper.mylooper (); //remove Looper if (mlooper = = throw new runtimeexception (  "Can ' t create handler inside thread that have not called looper.prepare ()"); } mqueue = Mlooper.mqueue; //take out messagequeue mcallback = callback; masynchronous = async;} //2, pass a looper come in public handler (looper Looper, Callback Callback, Boolean async) {mlooper = Looper; mqueue = looper.mqueue; mcallback = callback; masynchronous = async; }
Message

Single necklace table structure.

Role:

    • The carrier of the data
1. How is the message reused?

From the global message pool (linked list structure)

Obtain() {   new Message ();} 
2. Why can I send a message?

Android wants to pass an object either implemented serializable or parcelable, where the Parcelable interface is implemented.

Slightly
3, how to associate with handler?

We know that in the message transmission Mechanism handler act as a "courier" role, then how he and "Cargo"--message? In fact, the message has a member variable target whose type is handler,

/*package*/Runnable callback;    int arg2;  public Object obj; //Key points  

When we send a message through handler, the target is eventually assigned the value of this, the current handler.

Enqueuemessageif (masynchronous) {msg.setasynchronous (queue.enqueuemessage (MSG, Uptimemillis);} 

Also, if it is passed Message.obtain (), the multiplexed message obtained will be assigned a value.

One more word, handler.obtainmessage () is called Message.obtain ().

Obtainmessage() {    return Message.obtain (this);}  
Summarize:

Through a series of inclusion relationships, the final looper, Handler, message, and MessageQueue are associated, thus forming a closed, open message loop.

Confused

"Reprint" Summary of message mechanism issues that each Android developer must know

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.