Android-depth understanding of message processing system - Looper. Handler.Thread

Familiar with Windows programming friends may know that Windows is a message-driven program, and has a global message loop system. The Android application is message-driven, it stands to reason that the mechanism should also provide a message loop. Google actually refer to the Windows message loop system, Android system is also implemented in the message loop mechanism. Android by Looper, Handler mechanism to implement the message loop, Android is for the message loop thread (each thread can have its own message queue and message loop). This in-depth introduction Android messaging system works.

Looper Android system is responsible for managing the thread's message queue and message loop, see Looper concrete realization of the source. By Loop.myLooper () to get the current thread Looper object, Loop.getMainLooper () can get current process's main thread Looper object.

Mentioned earlier, the Android system message queue and message loop thread are specific, a thread can exist (and can not exist) a message queue and a message loop (Looper), a particular thread of messages can only be distributed to the thread , can not be cross-threaded, cross-process communication. However, the work created by default is no message loop thread and message queue, if you want the thread with the message queue and message loop, you need to thread the first call Looper.prepare () to create a message queue, and then call Looper.loop () into the message loop. The following example:

class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here


So your thread has a message processing mechanism, and for the Handler in the message processing.

Activity is a UI thread, running on the main thread, Android system will start when the Activity to create a message queue and message loop (Looper). See detailed implementation documents.

Handler's role is to add specific information (Looper) message queue, and distribute and process the message queue the message. Handler structure can be specified when the object is a Looper, if you do not specify the use of the current thread Looper created. Please refer to the detailed implementation Looper's source.

Activity, Looper, Handler relationship as shown below:

An Activity can create multiple threads or other components, if these threads or messages into their components of the main thread message queue Activity, then the message will be handled in the main thread. Because the main thread is generally responsible for the interface update, and Android system wiget not thread safe, so this approach can achieve a good Android interface updates. In the Android system has wide application in this way.

Then another thread how to put the message into the main thread's message queue? The answer is through the Handle object, as long as the Handler object to create the main thread Looper, then call the sendMessage Handler and other interfaces, will be the message in the queue would be placed in the main thread's message queue. Handler and the main thread will call the handler's handleMessage interface to handle the message.

This involves the thread synchronization problems, please refer to the following example to understand the threading model of the Handler object:

1, first create MyHandler project.

2, in add the following code:

package com.simon;

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)
                case HANDLER_TEST:
                        Log.d(TAG, "The handler thread id = " + Thread.currentThread().getId() + "\n");

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

        new myThread().start();

    class myThread extends Thread
        public void run()
                Message msg = new Message();
                msg.what = HANDLER_TEST;
                Log.d(TAG, "The worker thread id = " + Thread.currentThread().getId() + "\n");

In this case we are mainly print, this processing mechanism in which the threads of each module the situation. Here are the results 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, the message handler can safely call the main thread of any resources, including refreshed interface. Worker threads and main thread running in different threads, so you must pay attention to this competitive relationship between two threads.

The above example, you may have noticed in the worker thread to access the main thread handler object and the object in the call handler added to the message queue a message. This process will not occur in the message queue data inconsistency problem? The answer is the object handler will not go wrong, because the handler object management Looper objects are thread-safe, either by adding a message to the message queue and read messages from queues are protected with synchronization objects, please refer to specific file. Did not modify the example handler object, so the handler object is not likely the problem of inconsistent data.

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

1, if the thread through the work refreshed interface, recommended handler objects to achieve.

2, attention to the working thread and the competition between the main thread. Recommended handler object is constructed in the main thread to complete (and then start the worker threads do not modify it, otherwise there will be data inconsistency), then you can rest assured in the worker thread calls SendMessage to send messages and other interfaces.

3, in addition to 2 above the hanlder object outside of any member variables of the main thread if the calling thread at work, carefully consider the problem of thread synchronization. Need to be added if necessary to protect the variable synchronization objects.

4, handler object handleMessage interface will be in the main thread calls. In this function, the main thread can safely call any variables and functions, and then update the UI to complete the task.

5, Android API also use many features Handler this thread as a variant of the callback function to notify the caller. Android framework so you can send a message to the thread will be the caller's message queue of the thread, do not worry about thread synchronization problems.

In-depth understanding of message processing mechanism for Android application development is very important, but also allows you to synchronize threads to have a more profound understanding.

分类:Industry 时间:2011-09-19 人气:272
blog comments powered by Disqus


  • android thread Handler Message + = Queue AsyncTask thread model thread interactions + Button style changes easy integration of the final version of example 2010-11-26

    First of all forgive me for writing the title of the article so long. In fact, I still find it too short because it can not be written out so I will not write. Because I really do not know how to define the title of this article may be called "Luanta

  • Principle and Application of Linux Message Queue 2010-07-02 1, the basic concept of message queues Message Queuing (also known as message queues) is the Unix System V versions of three kinds of inter-process communication mechanisms. The other two are signal and shared memory.

  • Android's Message Queue 2008-05-15

    1. Message Queue role l in your Android program, the new birth of a thread, or thread (Thread), we will not automatically establish its Message Loop. l Android, and there is no Global Village of the Message Queue data structure, for example, differen

  • epoll + message queue - through the use of a simple implementation pthread_cond_signal 2010-06-27

    The first to implement a server with epoll, Prior to the use of epoll is not clear, Learn epoll servers found after the main thread in fact the best and deal with business code separate That is: io response to outside requests for epoll, when epoll g

  • linux message queue (Review ...) 2010-11-02

    Review of, not sure ... Little sad ... Process management of message queue View ipc object commands are: View shared memory ipcs-m ipcs-q View Message Queue semaphores ipcs-s View ipc object manipulation, such as deleting ipcrm-q id number Create a m

  • linux message queue analysis 2010-07-06

    Basic concept 1. Queuing Message queue is a linear form, it's access order is the first in first out (FIFO). That is, into the queue The first data item will be read from the queue out the first data item into the second will be read the second, acco

  • Utilize Android's Message Queue (1) 2010-11-17

    1. Message Queue role l Android in your program, the new to create a thread, or threads (Thread) time, and does not automatically establish the Message Loop. l Android is not in the Message Queue Global data structure, for example, different objects

  • Utilize Android's Message Queue (2) 2010-11-17

    1. Review the role Message Queue In the previous years, introduced the Android's Thread, Looper, Message Queue, and the relationship between the four Handler. First review as follows: l UI thread is usually the main thread, and Android to start a pro

  • [Transfer] Message Queue (Microsoft Message Queue) 2011-05-20

    Message Queue (Microsoft Message Queue) Message Queue (Microsoft Message Queue) is in a number of different applications to communicate between an asynchronous transfer mode, distributed applications can communicate with each other on the same machin

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C), All Rights Reserved. 版权所有 闽ICP备15018612号

processed in 0.437 (s). 10 q(s)