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() {
          Looper.prepare();

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

          Looper.loop();
      }
  }

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 ActivityThread.java 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 MyHandler.java add the following 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)
        {
                switch(msg.what)
                {
                case HANDLER_TEST:
                        Log.d(TAG, "The handler thread id = " + Thread.currentThread().getId() + "\n");
                        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() + "\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");
        }
    }
}


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 Looper.java 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.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

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

  • Hibernate access picture sample

    General web users to upload picture at treatment would normally uses two types of strategies: First, put directly into the picture in the database Blob field; II database are stored only at the picture on the path of the server information?, Pictures stor

  • hibernate query cache

    hibernate query cache Query cache is cached result set of common property On the entity object cache only the result set id Query cache life cycle, when the associated table happened to amend, then the query cache of the life cycle of The End Query cache

  • hibernate how to store binary, image and other major fields.

    model categories: reportByte binary type for the database fields. public class PfReportStyle implements java.io.Serializable , Cloneable { // Fields /** * */ private static final long serialVersionUID = 1L; private Long id; private byte[] reportByte; // C

  • Rails source code analysis (4): Request / Response

    1) Rails defines two abstract class: AbstractRequest and AbstractResponse code is not posted, first take a look at Response. 2) is mainly responsible for the specific ctgi_process.rb main interface is responsible for implementation methods of impleme ...

  • hibernate study of the second

    Persistence of three main points: 1, a statement for persistent fields accessors (accessors) and whether the variable signs (mutators) Property statement is not necessarily required for the public's. Hibernate can be default, protected or private ...

  • Use Ext JS to read the JsonReader complex object json

    Today was how to resolve the following complex json object to the difficult living over a long time .. did not find documentation how to read JsonReader Ways json object (possibly also because of their limited level of E the text did not correctly underst

  • hibernate (jpa) composite primary key annotation statement Ways

    In the design of the database tables are designed with a composite primary key of the table, that table's record by more than one field joint identification, such as: Table CREATE TABLE TB_HOUR_DATA ( STAT_DATE DATE NOT NULL, PATH_ID NUMBER(20) NOT NULL,

  • NoClassDefFoundError: javax / servlet / Servlet

    In the project in order to achieve a listener in web.xml set up a listener, did start in Tomcat actually occurred after java.lang.NoClassDefFoundError: javax / servlet / ServletContextListener this anomaly google and found the reasons for the lack of serv

  • jboss ejb3 Message Driven Bean

    Super Medium ejb hate. . . . . . . . . . . . . . . . . . . ================================================ To configure a Message Driven Bean in a different application server parameters are not the same. Currently only passed the test jboss. Message Dri

  • hibernate generic generic DAO

    package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries