The handler of Android message mechanism

Source: Internet
Author: User

Why Android has to provide handler

Android recommends that we do not take time-consuming actions in the UI thread because it can easily lead to a ANR exception (in the Android source code we see that the UI will report a ANR exception if the user's operation is not responding for more than 5 seconds). Therefore, some time-consuming operations are done in the child threads. When we get the data in a child thread, it is difficult to do so if there is no handler to display it in the UI. As a result, Android provides handler to solve the problem of child threading accessing the UI.
Why doesn't Android allow access to the UI in child threads? Obviously this is not safe, multithreaded access to the UI is not secure (learn the operating system of the pot friends should all understand the thread mutex, here I do not detail). Someone will say, you can set the signal amount to solve AH. This method is not an option, because this approach complicates the logic of accessing the UI, and secondly, it reduces the efficiency of the UI's access. The use of handler is relatively simple and efficient. Handler is the same message to communicate.

The use of handler

When using handler, you need to override the Handlemessage method, accept the message from the new thread in Handlemessage, and do the appropriate processing. Messages are passed through a message in a new thread, which often carries the data that needs to be passed along with the type of message. Also emphasize that if the current thread has looper do not need to execute looper.prepare (), if not, you need to execute looper.prepare () within the new thread, otherwise it will be an error. The following code is used:

1  Public classMainactivityextendsappcompatactivity {2     PrivateHandler mhandler=NewHandler () {3 @Override4          Public voidhandlemessage (Message msg) {5             Switch(msg.what)6             {7                  Case1:8                     //perform UI actions that require modification9                      Break;Ten                 default: One                      Break; A             } -         } -     }; the  - @Override -     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); + Setcontentview (r.layout.activity_main); -  +         NewThread (NewRunnable () { A @Override at              Public voidRun () {//take a time-consuming action in a new thread -  -                 //if the current thread has looper there is no need to execute looper.prepare (); - Looper.prepare (); -                 Try { -Thread.Sleep (1000);//Sleep 1 seconds in}Catch(interruptedexception e) { - e.printstacktrace (); to                 } +  -                 //notifies handler for UI action by sending a message after the operation is complete the  *Message msg=NewMessage (); $Msg.what=1;Panax Notoginseng  -                 /*This part is pseudo-code, value is what you want to pass through the message the bundle Data=new Bundle (); + data.putserializable ("key", value); A msg.setdata (data); the  +                 */ -  $                 //after setting the data, send the message. $ mhandler.sendmessage (msg); -             } - }). Start (); the     } - Wuyi}
The internal mechanism of handler

Handler is created with Looper to establish a message loop. Therefore, the current thread must have looper. When handler is created, its internal looper and MessageQueue can work together with handler. Handler sends the message to the internal MessageQueue through SendMessage, and MessageQueue calls the Queue.enqueuemessage (msg, Uptimemillis) method, which has the following source code:

1 BooleanEnqueuemessage (Message msg,LongWhen ) {2         if(Msg.target = =NULL) {3             Throw NewIllegalArgumentException ("Message must has a target."));4         }5         if(Msg.isinuse ()) {6             Throw NewIllegalStateException (msg + "This message was already in use."));7         }8 9         synchronized( This) {Ten             if(mquitting) { OneIllegalStateException e =NewIllegalStateException ( AMsg.target + "Sending message to a Handler on a dead thread"); - LOG.W (TAG, E.getmessage (), e); - msg.recycle (); the                 return false; -             } -  - msg.markinuse (); +Msg.when =When ; -Message p =mmessages; +             BooleanNeedwake; A             if(p = =NULL|| When = = 0 | | When <p.when) { at                 //New Head, Wake up the event queue if blocked. -Msg.next =p; -Mmessages =msg; -Needwake =mblocked; -}Else { -                 //Inserted within the middle of the queue. Usually we don ' t has to wake in                 //Up the event queue unless there are a barrier at the head of the queue -                 //The message is the earliest asynchronous message in the queue. toNeedwake = mblocked && P.target = =NULL&&msg.isasynchronous (); + Message prev; -                  for (;;) { thePrev =p; *p =P.next; $                     if(p = =NULL|| When <p.when) {Panax Notoginseng                          Break; -                     } the                     if(Needwake &&p.isasynchronous ()) { +Needwake =false; A                     } the                 } +Msg.next = p;//Invariant:p = = Prev.next -Prev.next =msg; $             } $  -             //We can assume mptr! = 0 because mquitting is false. -             if(needwake) { the Nativewake (mptr); -             }Wuyi         } the         return true; -}

Through the source, we found that Queue.enqueuemessage (msg, uptimemillis) put the message into the MessageQueue. Looper will always process the messages in the MessageQueue.

The handler of Android message mechanism

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.