这个是android API 对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.
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
意思就是说:Handler类允许你发送以及处理一个消息,每个Handler对象都和唯一的一个线程相关联。每当你创建一个Handler对象的时候,这个对象将会和你创建它所在的线程以及该线程的消息队列相互关联。
Handler主要用在消息调度以及一些耗时操作上。
一般的用法是:
一个小例子:
package com.seclab.testhandler;
import android.R.color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.Button;
public class MainActivity extends Activity {
Button btn;
MyHandler myHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button1);
myHandler = new MyHandler();
MyThread myThread = new MyThread();
new Thread(myThread).start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) { //处理消息
// TODO Auto-generated method stub
super.handleMessage(msg);
Log.e("xiaotao", "handler message");
Bundle bundle = msg.getData();
String colorString = bundle.getString("color");
MainActivity.this.btn.append(colorString);
}
public MyHandler() {
}
public MyHandler(Looper lp) {
super(lp);
}
}
class MyThread implements Runnable {
@Override
public void run() {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
Log.e("xiaotao", "thread is running");
Message msgMessage = new Message();
Bundle bundle = new Bundle();
bundle.putString("color", "红色的aaaaaaaaaa");
msgMessage.setData(bundle);
MainActivity.this.myHandler.sendMessage(msgMessage);发送消息
}
}
}