Handler的理解

 

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue. 

Handler使你能够send 和 处理 与一个线程的消息队列相关的Message和Runnable对象。每一个Handler实例是和一个指定线程及其消息队列相关联的。Handler对象会被绑定到创建它的thread及其消息队列。然后你就可以delivere Message and Runnable 对象,handler 会按照顺序依次处理这些他们。

 

 

下面是实现的小例子

 

package hust.ophone.RunnableTry;

 

import android.app.Activity;

import android.os.Bundle;

import android.os.Handler;

import android.os.Looper;

import android.os.Message;

import android.os.SystemClock;

import android.util.Log;

 

public class RunnableTry extends Activity {

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        sendMessage();

     } 

 

     public void sendMessage() {

        MHandler mHandler = new MHandler();

//Returns a new Message from the global message pool. More efficient than creating and allocating new //instances. The retrieved message has its handler set to this instance (Message.target == this).

        Message msg = mHandler.obtainMessage();

        Log.v("TAG", msg.toString());

        msg.sendToTarget();

     }

     class MHandler extends Handler {

        public MHandler() {

        } 

        public MHandler(Looper l) {

          super(l);

        } 

        @Override

        public void handleMessage(Message msg) {

          int count = 0;

          while (count++ < 10) {

             Log.d("TAG", "处理消息");

          }

        }

     } 

}

 

你可能感兴趣的:(thread,android,OS,OPhone)