Android Messaging Mechanism Handler

Source: Internet
Author: User
Tags message queue

Android's messaging mechanism--handler:handler is a class that the Android SDK provides to developers for easy asynchronous message processing.

A Why use Handler
1. Message mechanism: communication between different threads. Then the introduction of the Android message mechanism can be used handler mechanism to outline.
2. Why does Android use the handler mechanism: avoid ANR.
3. The way to avoid ANR is that the child threads perform time-consuming operations, and the UI is updated with the main thread through the handler mechanism.
4. Why the child thread cannot execute the UI: Because UI controls are not thread-safe, multi-line concurrency can result in unexpected results for the UI.
5. Why UI controls are not designed to be thread-safe: Because the design is thread-safe, the first UI performance is inefficient, followed by a kind of killing chicken with sledgehammer feeling, UI design is adhering to the simple and effective principle, then contrary to design.

Second, several key classes in Handler (Handler, Looper, MessageQueue, Message, ThreadLocal):

1. From the perspective of Use handler is: Establish handler rewrite Handlermsg method to process the message, through the thread sendmsg.
2.Handler Features:
There is no global message queue in a.android, and each activity has a separate message queue with the principle of FIFO. Different apk cannot be handle for message delivery.
B. Each handler instance is bound to the thread that created it.
C.handler sends a message to the message queue, and each massage is sent to the queued use FIFO principle. Sending a message asynchronously does not block the thread, and accepting the message synchronously blocks the thread, that is, handler finishes processing a Mesage message object before it goes to fetch
The next message is processed.
    
3. For several commonly used classes, the function is as follows:
Handler responsible for sending and processing messages
Looper the message pump, the message will be recycled to the handler to handle the messages taken. When there is no message, it will be in a blocking state.
MessageQueue Message Queuing, which is responsible for accessing messages.
Message that is sent specifically.
Threadlocal It is primarily used for data isolation between threads, where it stores the corresponding looper in each thread.

Three Examples of commonly used handler message processing are explained.
According to several commonly used handler message passing usage way to explain.
First create an activity, in the Activity Instance 3 button, respectively, processing several commonly used types of handler.

1. The main thread establishes handler for personal use. 2. The child thread obtains the looper of the parent class through Looper.getmainlooper () to establish handler.3. The handler of the main thread is passed to the child thread for communication.

 Public classMainactivityextendsActivityImplementsonclicklistener{Button MHandlerButton1=NULL; Button MHandlerButton2=NULL; Button MHandlerButton3=NULL;    Handler MyHandler;    Message msg; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (r.layout.activity_main1); MHandlerButton1=(Button) Findviewbyid (R.id.handler_button1); Mhandlerbutton1.setonclicklistener ( This); MHandlerButton2=(Button) Findviewbyid (R.id.handler_button2); Mhandlerbutton2.setonclicklistener ( This); MHandlerButton3=(Button) Findviewbyid (R.id.handler_button3); Mhandlerbutton3.setonclicklistener ( This); }     Public voidOnClick (View v) {if(v = =MHandlerButton1) {MyHandler=NewMyHandler (); Msg= Myhandler.obtainmessage (1, "ThreadMain handler");        Msg.sendtotarget (); }Else if(v = =MHandlerButton2) {Innerthread Innerthread=NewInnerthread ();        Innerthread.start (); }Else if(v = =MHandlerButton3) {MyHandler=NewMyHandler (); MyThread MyThread=NewMyThread (MyHandler);        Mythread.start (); }    }    Private classInnerthreadextendsthread{@Override Public voidrun () {//MyHandler = new MyHandler ();//you can only create Hanler objects within the main thread without Looper objects. If you use this here, it throws an exception .//MyHandler = new MyHandler (Looper.mylooper ());//Looper.mylooper get Looper to nullMyHandler =NewMyHandler (Looper.getmainlooper ());//get Looper of parent class to successfully create handler and send Messagemsg = Myhandler.obtainmessage (2, "Innerthread handler");        Msg.sendtotarget (); }    }    Private classMyThreadextendsthread{PrivateHandler Innerhandler;  PublicMyThread (Handler Handler) { This. Innerhandler = handler;//gets the handler of the main thread through the constructor and sends it to the main thread. } @Override Public voidrun () {msg= Innerhandler.obtainmessage (3, "MyThread handler");        Msg.sendtotarget (); }    }     Public classMyHandlerextendshandler{ PublicMyHandler (Looper mylooper) {Super(Mylooper); }         PublicMyHandler () {}//@Override Public voidhandlemessage (Message msg) {Switch(msg.what) { Case1: LOG.D ("Handlermessage", "this handler are in main thread");  Break;  Case2: LOG.D ("Handlermessage", "This handler was in Innerthread");  Break;  Case3: LOG.D ("Handlermessage", "This handler was in MyThread");  Break; default:                  Break; }        }    }
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "Vertical" > <Button Android:id= "@+id/handler_button1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "@string/handlerbutton1"/> <Button Android:id= "@+id/handler_button2"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "@string/handlerbutton2"/> <Button Android:id= "@+id/handler_button3"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "@string/handlerbutton3"/> </LinearLayout>

In terms of handler traits, handler mainly asynchronously handles more time-consuming operations, giving priority to returning the interface to the customer and updating the UI after processing is complete.

Android Messaging Mechanism Handler

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.