A deep understanding of the Android Message Processing System-Logoff, Handler, and Thread

Source: Internet
Author: User

Friends familiar with Windows programming may know that Windows programs are message-driven and have a global message loop system. Android applications are message-driven, and the message loop mechanism should also be provided. In fact, Google refers to the Message Loop Mechanism of Windows and implements the message Loop Mechanism in Android. Android uses logoff and Handler to implement the message loop mechanism. Android message loops are targeted at threads (each thread can have its own message queue and message loop ). This article introduces the principles of the Android Message Processing System in depth.

In the Android system, logoff is responsible for managing the message queues and message loops of threads. For specific implementation, see logoff source code. You can use Loop. myLooper () to obtain the Looper object of the current thread, and use Loop. getMainLooper () to obtain the Looper object of the main thread of the current process.

As mentioned above, message queues and message loops in the Android system are for specific threads. A thread can exist (or may not exist), a message queue, and a message loop ), messages of a specific thread can only be distributed to this thread. messages of a specific thread cannot communicate across threads or processes. However, the created worker thread does not have message loops or message queues by default. To enable this thread to have message queues and message loops, you must first call logoff in the thread. prepare () to create a message queue, and then call logoff. loop () enters the message loop. For example:

Class LooperThread extends Thread {
Public Handler mHandler;

Public void run (){
Logoff. prepare ();

MHandler = new Handler (){
Public void handleMessage (Message msg ){
// Process incoming messages here
}
};

Logoff. loop ();
}
} In this way, your thread has a message processing mechanism and processes messages in Handler.

An Activity is a UI thread that runs in the main thread. When the Android system starts the Activity, it creates a message queue and a message loop ). For detailed implementation, see the ActivityThread. java file.

Handler is used to add a message to a specific logoff message queue and distribute and process the messages in the queue. When constructing a Handler, you can specify a logoff object. If this parameter is not specified, the logoff object of the current thread is used. For detailed implementation, see logoff source code.

Shows the relationship between Activity, logoff, and Handler:

 

Multiple worker threads or other components can be created in an Activity. If these threads or components put their messages into the active thread message queue of the Activity, the message will be processed in the main thread. Because the main thread is generally responsible for interface update operations, and weget In the Android system is not thread-safe, this method can be used to implement Android interface update. This method is widely used in Android systems.

So how does another thread put messages into the message queue of the main thread? The answer is through the Handle object. As long as the Handler object is created with the Logoff of the main thread, calling the sendMessage and Other interfaces of Handler will put all messages in the queue into the message queue of the main thread. In addition, the handleMessage interface of the Handler will be called in the main thread of the handler to process the message.

This involves thread synchronization. First, refer to the following example to understand the thread model of the Handler object:

1. Create a MyHandler project.

2. Add the following code to MyHandler. java:

Package com. simon;

Import android. app. Activity;
Import android. OS. Bundle;
Import android. OS. Message;
Import android. util. Log;
Import android. OS. Handler;

Public class MyHandler extends Activity {
Static final String TAG = "Handler ";
Handler h = new Handler (){
Public void handleMessage (Message msg)
{
Switch (msg. what)
{
Case HANDLER_TEST:
Log. d (TAG, "The handler thread id =" + Thread. currentThread (). getId () + "");
Break;
}
}
};

Static final int HANDLER_TEST = 1;
/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
Log. d (TAG, "The main thread id =" + Thread. currentThread (). getId () + "");

New myThread (). start ();
SetContentView (R. layout. main );
}

Class myThread extends Thread
{
Public void run ()
{
Message msg = new Message ();
Msg. what = HANDLER_TEST;
H. sendMessage (msg );
Log. d (TAG, "The worker thread id =" + Thread. currentThread (). getId () + "");
}
}
} In this example, we mainly print the thread of each module of this processing mechanism. The following is the running result of my machine:

09-10 23:40:51. 478: DEBUG/Handler (302): The main thread id = 1
09-10 23:40:51. 569: DEBUG/Handler (302): The worker thread id = 8
23:40:52 09-10. 128: DEBUG/Handler (302): The handler thread id = 1 we can see that message processing is handled in The main thread, the message processing function can safely call any resources in the main thread, including refreshing the interface. The worker thread and the main thread run in different threads. Therefore, pay attention to the competition between the two threads.

In the preceding example, you may notice that the main thread handler object is accessed in the working thread, and a message is added to the Message Queue to the handler object. Will there be data inconsistency in the message queue during this process? The answer is that the handler object will not be faulty, because the logoff object managed by the handler object is thread-safe. Whether it is added to the Message Queue or read from the queue, the synchronization object is protected, for more information, see logoff. java file. In the preceding example, the handler object is not modified, so the handler object cannot have data inconsistency.

Through the above analysis, we can draw the following conclusions:

1. If you use a worker thread to refresh the interface, handler objects are recommended.

2. Pay attention to the competition between the working thread and the main thread. It is recommended that the handler object be constructed in the main thread (and do not modify it after the working thread is started; otherwise, data inconsistency will occur ), then, you can safely call interfaces such as SendMessage.

3. If the member variables of any main thread other than the hanlder object described in section 2 are called in the working thread, the thread synchronization issue should be carefully considered. If necessary, add a synchronization object to protect the variable.

4. The handleMessage interface of the handler object will be called in the main thread. In this function, you can call any variables and functions in the main thread with confidence to complete the UI update task.

5. Many Android APIS also use the Handler thread feature as a callback function variant to notify callers. In this way, the Android framework can send messages to the caller's thread message queue in its thread without worrying about thread synchronization.

An in-depth understanding of the Android message processing mechanism is very important for application development. It also gives you a deeper understanding of thread synchronization. The above is a summary of Simon's recent study of the Android message processing mechanism. If there are any errors, please do not hesitate to advise.

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.