[Androidthread&handler] thread2-Case 1

Source: Internet
Author: User

Android Message Queuing model Thread,handler,looper,massage queue

Both the message queue and message loop for the Android system are for a specific thread, and a thread can exist (and, of course, not exist) a message queue and a message loop (Looper). In addition to the UI thread (the main thread) in Android, the worker threads created by default have no message loops and message queues. If you want the thread to have Message Queuing and message loops and have a message-handling mechanism, you will need to call Looper.prepare () in the threads first to create the message queue, and then call Looper.loop () to enter the message loop. As shown in the following code:

Java Code   

class LooperThread extendspublicpublic void run() { Looper.prepare();  // 创建消息队列 mHandler = newpublic void handleMessage(Message msg) { // process incoming messages here  

This allows the thread to have a message-handling mechanism. If you do not call Looper.prepare () to create a message queue, it will be reported "Java.lang.RuntimeException:Can ' t create handler inside thread that have not called Looper.prepare () "error.

The relationship between UI thread, Worker Thread, Handler, massage Queue, Looper can be clearly displayed:

Several basic concepts in the interpretation:

1.Message message

A Message object, as the name implies, is the class that records message information. There are several more important fields for this class:

A.arg1 and Arg2: We can use two fields to hold the integer value we need to pass, and in the service we can store the service ID.

B.obj: This field is an object type, and we can let the field pass a number of items to the recipient of the message.

C.What: This field can be said to be a message flag, in the message processing, we can be based on the different values of this field to do different processing, similar to when we handle the button event, through switch (V.getid) to determine which button is clicked.

When using the message, we can create a message instance from the new message (), but Android recommends that we pass the Message.obtain () or Handler.obtainmessage () Gets the message object. This is not necessarily a direct creation of a new instance , but rather there is no available message instance from the message pool , and the instance is directly fetched and returned. Conversely, if there is no message instance available in the pool, a new message object is given according to the parameter. By analyzing the source, it is known that the Android system instantiates a total of ten message objects in the messaging pool by default.

2.Message Queue Message Queuing

Message Queuing, which holds the data structure of the message object and stores the message according to the "FIFO" principle. Storage is not a meaningful save, but instead the message object is concatenated in a linked list . The message Queue object does not need to be created by ourselves, but rather has a Looper object to manage it, and a thread can have at most one message queue. We can pass the Looper. Myqueue () Gets the message Queue in the current thread .

3.Looper

Message Queu Manager, in a thread, if there is a Looper object, there must be a message queue object, and there is only one Looper object and one MessageQueue object. If the Looper object exists in our thread, we can get it through Looper.mylooper (), and we can get the Looper object of the main thread in the current application via Looper.getmainlooper (). One thing to note in this place is that if the Looper object is in the main thread of the application, Looper.mylooper () and Looper.getmainlooper () get the same object.

4.Handler

The processor of the message. Through the handler object we can encapsulate the message object and then add the message object to the MessageQueue through SendMessage (msg), and when MessageQueue loops to the message, The Handlemessage () method of the handler object corresponding to the message object is called to process it. Because the messages are processed in the Handlemessage () method, we should write a class that inherits from handler and then handles the operations we need in Handlemessage ().

In addition, we know that the Android UI operation is not thread-safe, so it is not possible to update the UI in a child thread . However, Andriod provides several ways to notify the UI thread update interface in a child thread :

    • Activity.runonuithread (Runnable)
    • View.post (Runnable)
    • View.postdelayed (Runnable, long)
    • Handler

It is more common to use handler to receive the data sent by the handler, and to update the UI with this data in conjunction with the main thread. Then, as long as the handler object is created in the main thread and the SendMessage method of handler is called in the child thread, the message is placed in the message queue of the main thread. The handler's Handlemessage method will be called in the handler main thread to process the message.

Java Code  

  PackageHome.lee.thread;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Message;ImportAndroid.util.Log;ImportAndroid.os.Handler; Public classMyHandlerextendsActivity {StaticFinalString TAG = "Raylee";StaticFinalString TITLE = "Handler";StaticFinalintHandler_test = 0x001; /** called when the activity is first created. */@Override Public voidOnCreate (Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);           Setcontentview (R.layout.main); Start a child threadNewMyThread (). Start ();         Print main thread ID         LOG.I (TAG + TITLE, "The main thread id =" + thread.currentthread (). GetId () + "\ n"); }//create Handler and message processing mechanism HandlerMyhander=NewHandler () { PublicvoidHandlemessage(Message msg) {Switch(msg. what) { CaseHandler_test://Verify thread ID is child thread log.i (TAG + TITLE, "the HANDLER thread id =" + thread.cu Rrentthread (). GetId () + "\ n"); Break;       }          }      }; Create child threads and messages, and pass the SendMessage method to the main threadclassMyThreadextendsthread{ PublicvoidRun () {Message msg =NewMessage (); Msg. What= Handler_test;Myhander. SendMessage (msg);          Print the child thread ID log.i (TAG + TITLE, "the worker thread id =" + thread.currentthread (). GetId () + "\ n"); }      }  }

In the code above, when handler is created in the main thread, the child thread can send the message to the main thread through the SendMessage () method and process it in the Handlemessage () method.

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.