Android message mechanism (handler, logoff, messagequeue, message)

Source: Internet
Author: User

Android message processing has three core classes: logoff, handler, and message. There is also a message queue, but MQ is encapsulated into logoff, handler plays the role of adding and processing messages to MQ (only processing messages sent by itself), that is, notifying MQ that it wants to execute a task (sendmessage ), and execute the handlemessage when the loop is reached. The whole process is asynchronous.

Shows the message processing process:

 

Handler mainly involves the following content:

Handler, handler. Callback, asyncqueryhandler

Logoff,

Handlerthread, runnable

Message and Message Queue

Logoff

Logoff In the android official documentation:

Class used to run a message loop for a thread. threads by default do not have a message loop associated with them; to create one, call prepare () in the thread that is to run the loop, and then loop () to have it process messages until the loop is stopped.

Most interaction with a message loop is through the handler class.

This is a typical example of the implementation of a logoff thread, using the separation of prepare () and loop () to create an initial handler to communicate with the logoff.

View code

 1 class LooperThread extends Thread { 2  3       public Handler mHandler; 4  5       public void run() { 6  7           Looper.prepare();  8  9           mHandler = new Handler() {10 11               public void handleMessage(Message msg) {12 13                   // process incoming messages here14 15               }16 17           };18 19           Looper.loop();20 21       }22 23 }

The logoff class in Android is a class used to encapsulate message loops and message queues. It is used to process messages in Android threads. Handler can be seen as a tool class used to insert messages to a message queue.

(1) The logoff class is used to enable a message loop for a thread.

By default, the new thread in Android does not enable the message loop. (Except for the main thread, the main thread system automatically creates a logoff object for it to enable message loop .) The logoff object stores messages and events through messagequeue. A thread can have only one logoff corresponding to one messagequeue.

(2) The Handler object is usually used to interact with logoff. Handler can be seen as an interface of logoff to send messages to a specified logoff and define the processing method.

By default, handler is bound to the loose of the thread in which it is defined. For example, if handler is defined in the main thread, it is bound to the loose of the main thread.

Mainhandler = new handler () is equivalent to new handler (loler. myloler ()).

Looper. mylooper (): gets the looper object of the current process. Similar Looper. getmainlooper () is used to obtain the looper object of the main thread.

(3) New handler () directly in a non-main thread will report the following error:

E/androidruntime (6173): uncaught handler: thread-8 exiting due to uncaught exception

E/androidruntime (6173): Java. Lang. runtimeexception: can't create handler inside thread that has not called loled. Prepare ()

The reason is that no logoff object is created by default in the main thread. You must first call logoff. Prepare () to enable logoff.

(4) logoff. Loop (); let logoff start to work, get the message from the message queue, and process the message.

Note: Write it in logoff. the code after loop () will not be executed. This function should be a loop. When mhandler is called. getlooper (). after quit (), the loop will be aborted, and the subsequent code can be run.

(5) Based on the above knowledge, the main thread can send messages to subthreads (non-main threads.

Declare the mhandler in the Code as a class member and send a message through mhandler in the main thread.

 

Handler

Handler is responsible for sending and processing messages in Android. Its main purposes include:

1) send a message as planned or execute a runnanble (using the POST method );

2) put messages sent from other threads into the message queue to avoid thread conflicts (often used in updating UI threads)

By default, Handler accepts the message loop instances in the current thread (using handler (loophtling), handler (loophtling, Handler. callback callback) can specify a thread). At the same time, a message queue can be distributed and processed by multiple objects in the current thread (in the UI thread, the system has an activity to process, you can initiate several handler operations ). When handler is instantiated, logoff can be any thread. As long as there is a handler pointer, any thread can also sendmessage. Handler does not process messages concurrently. A logoff reads the next message only after processing a message. Therefore, the processing of the message is a blocking (handlemessage () method, and there should be no time-consuming operations, the time-consuming operation can be executed in other threads. After the operation is completed, the message is sent (by using the sendmessges method), and then the handlemessage () is used to update the UI ).

Messages are processed by calling Post (runnable), postattime (runnable, long), postdelayed (runnable, long), sendemptymessage (INT), sendmessage (Message), sendmessageattime (message, long) and sendmessagedelayed (message, long. The post version method allows you to put the runnable object into the message queue. The sendmessage version method allows you to put a message object containing the bundle object into the message queue, then it is processed by the handlemessage (Message) method. (You need to re-write the handlemessage method of handler ).

 

1. Handler uses the POST method

View code

The program running result is:

From the results, we can see that the POST method is used to attach a runnable object to the main thread without opening a new thread. Note: If you perform time-consuming operations on the runnable object, the ANR dialog box is displayed.

 

2. Handler uses the sendmessage Method

Multiple sendmessage methods are available:

(1) Both handler and sendmessage are in the same thread.

(2) handler is in the main thread and sendmessage is in the subthread

(3) handler in the subthread and sendmessage in the main thread

In the first case, the handlemessage () method is overwritten when the handler object is created, or the main thread is used, so there cannot be time-consuming operations in message processing, otherwise, the ANR dialog box appears.

In the second case, a new thread is created to process time-consuming operations. The sample code is as follows:

View code

Handlerthread is involved in the third case. By default, Handler accepts the message loop instance under the current thread. To use the message queue of A subthread, handlerthread must be used, which inherits from the thread, the difference with a common thread is that it has a logoff member variable, which encapsulates the message queue and queue processing logic. Simply put, it is the message queue + message loop. (Handlerthread can be used when we need a working thread instead of using it as a disposable consumable. If it is used out, handlerthread can be used ).

 

Handlerthread

Logoff In the android official documentation:

Handy class for starting a new thread that has a logoff. The logoff can then be used to create handler classes. Note that start () must still be called.

The run method code in the handlerthread source code is as follows:

Public VoidRun (){
Mtid = process. Mytid();
Logoff. Prepare(); // Make the thread have a logoff object
Synchronized( This){
Mlogoff = logoff. Myloads();
Policyall ();
}
Process. Setthreadpriority(Mpriority );
Onlooperprepared ();
Logoff. Loop(); // Start logoff, fetch messages from the message queue, and process messages
Mtid =-1;
}

    The thread that inherits the class has the logoff member variable, which can process the messages sent by handler.

    View code

    The program running result is as follows:

     

     

    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.