A deep understanding of the android Message Processing System-Logoff, handler, and thread

Source: Internet
Author: User

(Self) activity, the service belongs to the main thread, in the main thread can update the UI, such as toast. Other threads cannot be used directly. handler can be used for processing, and handler can be used in activity and service.

There will be issues with UI operations in non-UI threads: can't create handler inside thread that has not called logoff. Prepare ()

There are two solutions:

(1) create a message queue in this non-UI thread (because the created working thread does not have a message loop or message queue by default), loose. prepare ();.....; logoff. loop (); 

 NewThread (){

PublicVoidRun (){

Logoff. Prepare (); // create a message queue

Todo ();

Logoff. Loop (); // enters the message loop

}. Start ();

(2) handler mechanism:

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)
{< br> switch (MSG. what)
{< br> case handler_test:
log. D (TAG, "the handler thread id =" + thread. currentthread (). GETID () + "\ n");
break;
}< BR >};

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 () + "\ n ");

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 () + "\ n ");
}
}
}

**************************************** ******************************** ****************

If you are familiar with windows programming, you may know windowsProgramIt is message-driven and has a global message loop system. Android applications are message-driven.
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
Logoff and handler are used to implement the message loop mechanism. The Android message loop is for threads (each thread can have its own message queue and message loop ). This article introduces
Principles of the android message processing system.

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
Logoff object.


As mentioned above, the message queues and message loops in the Android system are aimed at specific threads. A thread can exist (or may not exist), a message queue and a message loop.
(Logoff), messages of a specific thread can only be distributed to this thread, and cross-thread and cross-process communication is not allowed. However, the created worker thread does not have a message loop or message queue by default.
If there are message queues and message loops, You need to first call logoff. Prepare () in the thread to create a message queue, and then call logoff. Loop () to enter the message loop. Example
As shown in:

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:


You can create multiple worker threads or other components in an activity. If these threads or components put their messages in the active thread message queue of the activity, the message will
It is handled 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 effectively implement the android Interface
Area 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 in the Logoff of the main thread
Handler sendmessage and Other interfaces will put all messages in the queue into the message queue of the main thread. The handler will be called in the main thread of the handler.
Handlemessage interface to process messages.

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 to myhandler. Java:Code:

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)
{< br> switch (MSG. what)
{< br> case handler_test:
log. D (TAG, "the handler thread id =" + thread. currentthread (). GETID () + "\ n");
break;
}< BR >};

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 () + "\ n ");

New mythread (). Start ();
Setcontentview (R. layout. Main );
}

class mythread extends thread
{< br> Public void run ()
{< br> message MSG = new message ();
MSG. what = handler_test;
H. sendmessage (MSG);
log. D (TAG, "the worker thread id =" + thread. currentthread (). GETID () + "\ n");
}< BR >}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
09-10
23:40:52. 128: Debug/handler (302): the handler thread id =
1. We can see that message processing is handled in the main thread. In the message processing function, we can safely call any resources in the main thread, including refreshing the interface. The worker thread and the main thread run in different threads.
To 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 a Message Queue appear in this process?
What about column data inconsistency? 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 from the queue
Column-read messages are protected by synchronization objects. For details, refer to the logoff. Java file. In the preceding example, the handler object is not modified, so the handler object cannot contain
Consistency issues.

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.

From: http://blog.csdn.net/dywe_ddm/archive/2010/10/10/5930948.aspx

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.