Android Handler message transmission mechanism, androidhandler
1. A preliminary understanding of the Handler message transmission mechanism: What is Handler?
Handler is generally used to send data processing objects between threads. In any thread, as long as the handler of another thread is obtained, data can be sent to that thread through the handler. sendMessage (message) method. Based on this mechanism, we can create a thread when processing multiple threads, which has a handler in the UI thread. After processing some time-consuming operations, the thread sends data to the UI thread through the passed handler, And the UI thread updates the interface.
Main thread: runs all the UI components and completes this task through a message queue. The device converts each operation of a user to a message and puts them in a running message queue. The main thread is in a loop and processes each message. If any message takes more than 5 seconds, Android will throw ANR. Therefore, if a task takes more than five seconds, it should be completed in an independent thread, or it should be processed by delay. When the main thread is idle, It will be returned to process it.
2. Common classes:(Handler, logoff, Message, MessageQueue)
Message: contains the Message ID, the Message processing object, and the processed data. MessageQueue queues in a unified manner and is eventually processed by Handler.
Handler: the Handler responsible for sending and processing messages. When using Handler, you must implement the handleMessage (Message msg) method to process specific messages, such as updating the UI. The main functions of the Handler class are as follows: (two main functions) 1) send messages in the working thread; 2) Get w/fetch and process messages in the main thread.
MessageQueue: a message queue used to store messages sent by Handler and run the messages according to FIFO rules. Of course, storing the Message is not actually saving, but concatenating the Message, waiting for the logoff to be extracted.
Logoff: the Message pump constantly extracts messages from MessageQueue for execution. Therefore, a MessageQueue requires a logoff.
3. Relationships between Handler, logoff, Message, and MessageQueue:
- Logoff corresponds to MessageQueue one by one. When a logoff is created, a MessageQueue is created;
- The relationship between Handler and them is just a simple clustering relationship, that is, the Handler will reference the specific logoff and MessageQueue in the current thread;
- In a thread, there can be only one loose and MessageQueue, but there can be multiple Handler, and these Handler can share one loose and MessageQueue;
- Message is stored in MessageQueue. A MessageQueue can contain multiple Message objects.
[Note :]
The logoff object is used to enable a message loop for a thread to operate MessageQueue;
By default, the thread created by Android does not enable message loop logoff, but the main thread does not.
The system automatically creates logoff objects for the main thread to enable message loops;
Therefore, the main thread uses new to create a Handler object. However, if the Sub-thread cannot directly create a new Handler object, an exception occurs.
To create a Handler object in a child thread, follow these steps:
Logoff. prepare ();
Handler handler = new Handler (){
// Handlemessage (){}
}
Logoff. loop ();
4. Common Handler classes:
(1) handleMessage () is used in the main thread to override the handleMessage () method when constructing a Handler object. This method performs different operations based on the message identifier returned by the worker thread.
(2) sendEmptyMessage () is used in the work thread to send an empty message.
(3) sendMessage () is used in the work thread to send the message immediately.
5. common attributes of the Message class:
(1) arg1 is used to store Integer Data
(2) arg2 is used to store Integer Data
(3) obj is used to store Object data.
(4) what is used to specify the custom message code, so that the main thread can perform different operations based on the message code after receiving the message.
The Demo code is as follows:
Private Handler handler = null; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); text_main_info = (TextView) findViewById (R. id. text_main_info); pDialog = new ProgressDialog (MainActivity. this); pDialog. setMessage ("Loading... "); image_main = (ImageView) findViewById (R. id. image_main); // The handler object in the main thread processes the Me Ssage. Perform operations based on different numbers of messages. Handler = new Handler () {public void handleMessage (android. OS. message msg) {// all the messages to be sent in the work thread are placed in the Message object, that is, the msg parameter above. To perform the operation, you must first retrieve the data transmitted in msg. Switch (msg. what) {case 0: // The worker thread sends a message indicating that the thread is enabled. In the main thread, a progress dialog box pDialog. show (); break; case 1: // the information sent by the worker thread for what is 1 indicates that the thread has loaded the required data. In this case, you need to obtain the data and display it in the specified ImageView control. Image_main.setImageBitmap (Bitmap) msg. obj); break; case 2: // The worker thread sends the information of what is 2, which indicates that the worker thread ends. In this case, the main thread only needs to cancel the progress dialog box. PDialog. dismiss (); break ;}}; new Thread (new Runnable () {@ Override public void run () {// The Progress dialog box is displayed when the job Thread is started, in this case, let handler send an empty message. // When this message is sent, the main thread calls back the handleMessage () method in the handler object. In the handleMessage () method, // different operations are performed based on the type of message. Handler. sendEmptyMessage (0); // The worker thread executes the task of accessing the network and loading the network image. Byte [] data = HttpClientHelper. loadByteFromURL (urlString); // The worker thread generates Bitmap for the byte array obtained by network access. Bitmap bitmap = BitmapFactory. decodeByteArray (data, 0, data. length); // The information that the worker thread will send to the master thread is put into a Message object. // We recommend that you use the obtain () method to generate the Message object instead of the new method. Message msgMessage = Message. obtain (); // place the data to be passed to the main thread in the obj attribute of the Message object for transmission to the main thread. MsgMessage. obj = bitmap; // The what attribute of the Message object is used to differentiate information types and facilitate operations based on these types in the main thread. MsgMessage. what = 1; // The handler object carries the data in the Message and returns it to the main thread handler. sendMessage (msgMessage); // handler sends an empty message to tell the main thread that the job is completed. Generally, after the main thread receives the message, // close handler. sendEmptyMessage (2) ;}}). start () ;}in the progress dialog box ();}