Android Handler Message delivery mechanism

Source: Internet
Author: User

1. Handler message transmission mechanism Preliminary understanding: what is handler?
Handler popular point is the processing object used to send data between various threads. In any thread, the data can be sent to that thread by means of the handler.sendmessage (Message) method, as long as the handler of another thread is obtained. Based on this mechanism, we can create a new thread when dealing with multithreading, which has a handler in the UI thread. When thread finishes processing some time-consuming operations, it sends data to the UI thread by passing the handler, and the UI thread updates the interface.
main Thread: Runs all UI components that complete this task through a message queue. The device translates each user's actions into messages and puts them in a running message queue. The main thread is in a loop and processes each message. If any one message takes more than 5 seconds, Android will throw the ANR. So a task takes more than 5 seconds, it should be done in a separate thread, or deferred, when the main thread is idle and then returned to handle it.

2. Common classes:(Handler, Looper, Message, MessageQueue)
message: Messages that contain the message ID, the message Processing object, and the processed data are queued by MessageQueue and processed by handler.
Handler: Handler, responsible for sending and processing the message. When using handler, you need to implement the Handlemessage (Message msg) method to process a specific message, such as updating the UI. The main functions of the handler class are: (There are two main functions) 1), send messages in the worker thread, 2), receive w/in the main thread, and process the message.
MessageQueue: Message Queuing, which holds messages sent by handler and executes according to FIFO rules. Of course, storing a message is not a meaningful preservation, but rather a concatenation of the message, waiting for the looper to be extracted.
Looper: The message pump continuously extracts message execution from the MessageQueue. Therefore, a MessageQueue needs a looper.

3.Handler, Looper, Message, MessageQueue relationship:

    • Looper and MessageQueue one by one correspond, create a looper at the same time, will create a MessageQueue;
    • The relationship between handler and them is simply a gathering relationship, that is, Handler will refer to the specific looper and MessageQueue of the current line thread;
    • In a thread, there can be only one looper and MessageQueue, but there may be multiple handler, and these handler can share a looper and MessageQueue;
    • The message is stored in MessageQueue, and a MessageQueue can contain multiple message objects

"Remarks:"
The Looper object is used to open a message loop for a thread, thereby manipulating the MessageQueue;
By default, the thread created by Android does not have the message loop Looper turned on, but the main thread exception.
The system automatically creates the Looper object for the main thread and turns on the message loop;
So use new in the main thread to create the handler object. It is not possible to create a handler object directly from a child thread without a direct new.
To create a handler object in a child thread, proceed as follows:
Looper.prepare ();
Handler Handler = new Handler () {
Handlemessage () {}
}
Looper.loop ();

common methods in the 4.Handler class:
(1) Handlemessage () overrides the Handlemessage () method when constructing a handler object in the main thread. This method performs different actions, based on the message ID returned by the worker thread.
(2) Sendemptymessage () is used in the worker thread to send an empty message.
(3) SendMessage () is used in the worker thread to send the message immediately.

Common Properties in 5.Message message classes:
(1) arg1 for storing integer data
(2) arg2 for storing integer data
(3) obj for storing object data
(4) What is used to specify a user-defined message code so that after the main thread receives it, it performs different actions depending on the message code.

Try the sample code for the demo:

PrivateHandler Handler =NULL; @Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Text_main_info=(TextView) Findviewbyid (r.id.text_main_info); Pdialog=NewProgressDialog (mainactivity. This); Pdialog.setmessage ("Loading ..."); Image_main=(ImageView) Findviewbyid (R.id.image_main); //The handler object in the main thread processes the message sent in the worker thread. The corresponding action is based on the different numbers of the message. Handler =NewHandler () { Public voidhandlemessage (android.os.Message msg) {//The information to be sent in the worker thread is all placed in the Message object, which is the parameter msg above. To do this, the data passed in the MSG is taken out first.                         Switch(msg.what) { Case 0:                                //The message that the worker sends what is 0 indicates that the thread is turned on. A progress dialog box is displayed in the main thread accordinglypdialog.show ();  Break;  Case 1:                                //The worker thread sends what is 1 to indicate that the thread has finished loading the required data. In this case, you need to get the data to appear in the specified ImageView control. Image_main.setimagebitmap ((Bitmap) msg.obj);  Break;  Case 2:                                //The worker thread sends a message that what is 2 represents the end of the worker thread. In this case, the main thread simply cancels the progress dialog box. Pdialog.dismiss ();  Break;        }                }        }; NewThread (NewRunnable () {@Override Public voidrun () {//When the worker thread starts up, and wants to display the progress dialog box, let handler send an empty message. //when this message is sent, the main thread will callback the Handlemessage () method in the Handler object. In the Handlemessage () method//different actions are performed based on what kind of message. Handler.sendemptymessage (0); //The worker thread performs the task of accessing the network and loading the network pictures.                         byte[] data =Httpclienthelper.loadbytefromurl (urlstring); //The worker thread generates a bitmap bitmap of the byte array that the network access obtains. Bitmap Bitmap = Bitmapfactory.decodebytearray (data,0, data.length); //the information that the worker thread will send to the main thread is placed in a message information object. //the construction of the message object is recommended to be generated using the obtain () method, but not by using new. Message Msgmessage =Message.obtain (); //put the data that needs to be passed to the main thread into the Obj property of the Message object, so that it can be passed to the main thread. Msgmessage.obj =bitmap; //the What property of the message object is to distinguish the kind of information and to facilitate the corresponding operation of these categories in the main thread. Msgmessage.what =1; //the handler object carries the data in the message back to the main threadhandler.sendmessage (msgmessage); //handler sends out an empty message to tell the main thread that the task of the worker is finished. The general main thread will receive this message,//Close the Progress dialog boxHandler.sendemptymessage (2); }}). Start ();}

Android Handler Message delivery 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.