Handler principle Analysis and use (i.)

Source: Internet
Author: User

Why I write handler, the main reason is that it is very important throughout the Android application level, he is the main means of communication between the threads. It is most commonly used by other threads to update the main thread UI by sending messages to the main thread via handler.

Here is one of the simplest examples.

1 ImportAndroid.os.Handler;2 ImportAndroid.os.Message;3 Importandroid.support.v7.app.AppCompatActivity;4 ImportAndroid.os.Bundle;5 ImportAndroid.widget.TextView;6 7  Public classMainactivityextendsappcompatactivity {8 9     PrivateTextView Mytextview;Ten     PrivateHandler MyHandler =NewHandler () { One @Override A          Public voidDispatchMessage (Message msg) { -             //the UI thread received the message -             intArg1 =Msg.arg1; the             Switch(arg1) { -                  Case0: -                     if(Msg.arg2 = = 0){ -                         //Update UI + Mytextview.settext ((String) msg.obj); -                     } +                      Break; A                 default: at                      Break; -             } -             Super. DispatchMessage (msg); -         } -     }; - @Override in     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); to Setcontentview (r.layout.activity_main); +Mytextview = (TextView) This. Findviewbyid (R.id.text_view); -         //from a standalone thread the         NewThread () { *              Public voidrun () { $String Text = "from handler";Panax NotoginsengMessage message =NewMessage (); -MESSAGE.ARG1 = 0; theMESSAGE.ARG2 = 0; +Message.obj =text; A                 //send a message to the UI via handler the myhandler.sendmessage (message); +             } - }.start (); $     } $}

The above example looks so simple. But support for such messages from one line path to another, not just the support of handler such a class, but also the support of other classes, namely Looper, Message, MessageQueue.

Components of Message Flow:

The message is the entity of the messages.

MessageQueue Message Queuing.

Looper Each thread has only one, it does two things:

One is to create a MessageQueue that is provided to handler to add the message to MessageQueue.

The other is a different poll from the MessageQueue that reads the message passed to the handler dispatchmessage (message) for processing.

The flow of information

The first step is that the thread that needs to accept the message needs to be bound to looper. When the Activity (UI thread) starts, it creates its own Looper, and the Messsagequeue object created in the creation of New Looper (). The binding of the UI thread is to get the UI thread Looper in the new Handler () method. The non-UI thread needs to call Looper.prepare () to initialize the Looper object when Looper is enabled (note that initialization can only be called once). When initializing the Looper object, the MessageQueue object is created at the same time.

 PublicHandler () { This(NULL,false); }   PublicHandler (Callback Callback,Booleanasync) {          if(find_potential_leaks) {Finalclass<?extendsHandler> Klass =getclass (); if((Klass.isanonymousclass () | | klass.ismemberclass () | | klass.islocalclass ()) &&(Klass.getmodifiers ()& modifier.static) = = 0) {LOG.W (TAG,"The following Handler class should be static or leaks might occur:" +klass.getcanonicalname ()); }          }          //gets the Looper object for the thread. Mlooper =Looper.mylooper (); Mqueue=Mlooper.mqueue; Mcallback=callback; Masynchronous=Async; }  

The second step is to send a message via handler, that is, SendMessage (message) and other similar methods. These methods are finally called to the MessageQueue Enqueuemessage (...) to add the message to the message queue.

 Public Final BooleansendMessage (Message msg) {returnsendmessagedelayed (MSG, 0); }  Public Final BooleanSendemptymessagedelayed (intWhat,LongDelaymillis) {Message msg=Message.obtain (); Msg.what=what ; returnsendmessagedelayed (msg, delaymillis); } Public Final BooleanSendmessagedelayed (Message msg,LongDelaymillis) {         if(Delaymillis < 0) {Delaymillis= 0; }         returnSendmessageattime (MSG, systemclock.uptimemillis () +Delaymillis); }   Public BooleanSendmessageattime (Message msg,LongUptimemillis) {MessageQueue Queue=Mqueue; //msg is added to the MessageQueue object queue.        returnenqueuemessage (Queue, MSG, uptimemillis); }

In the third step, Looper polling gets the message out of the MessageQueue. The specific method is Looper.loop (), which finally calls to Msg.target.dispatchMessage (message), where Msg.target is the sender handler object of the Message object. Looper.loop () This method is obtained by acquiring the Looper object, further acquiring the messaagequeue inside the Looper object. It then polls the message inside the MessageQueue until the message is empty.

 Public Static voidLoop () {//Get Loop        FinalLooper me =Mylooper (); if(Me = =NULL) {              Throw NewRuntimeException ("No Looper; Looper.prepare () wasn ' t called on the This thread. "); }          //get the MessageQueue object inside the loop        FinalMessageQueue queue =Me.mqueue; //Make sure the identity of the the the the The local process,//And keep track of the What, identity token actually is. binder.clearcallingidentity (); Final LongIdent =binder.clearcallingidentity (); //Infinite loop Get message         for (;;) {Message msg= Queue.next ();//might block            if(msg = =NULL) {                  //No message indicates that the message queue is quitting.                 return; }                //This must is in a local variable with case a UI event sets the loggerPrinter logging =me.mlogging; //If there is a message, call handler's DispatchMessagemsg.target.dispatchMessage (msg); //Make sure that during the course of dispatching the//The identity of the thread wasn ' t corrupted.             Final LongNewident =binder.clearcallingidentity ();          Msg.recycle (); }  }

The fourth step, processing the message, invokes the DispatchMessage (message) method. Don't dwell on it.

In the above process need to pay attention to.

The message object itself exists in a pool of messages. If there is a message in the message pool, it is recommended that you do not use new to produce objects that should take the object

Message message == 0; myhandler.sendmessage (message);

Let's get here today. It's just part of the other part tomorrow. The same open-source component Eventbus as interprocess communication will also be analyzed.

Handler principle Analysis and use (i.)

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.