Handler的官方注释如下:
A Handler allows you to send and process
<a href="file:///F:/android%E5%AD%A6%E4%B9%A0/docs-3.0_r01-linux/docs/reference/android/os/Message.html">Message</a>
and Runnable objects associated with a thread’s<a href="file:///F:/android%E5%AD%A6%E4%B9%A0/docs-3.0_r01-linux/docs/reference/android/os/MessageQueue.html">MessageQueue</a>
. Each Handler instance is associated with a single thread and that thread’s message queue. Handler会关联一个单独的线程和消息队列。Handler默认关联主线程,虽然要提供Runnable参数 ,但默认是直接调用Runnable中的run()方法。也就是默认下会在主线程执行,如果在这里面的操作会有阻塞,界面也会卡住。如果要在其他线程执行,可以使用HandlerThread。
Handler使用方法:
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 处理发送过来的消息
Bundle b = msg.getData();
System.out.println("msg:" + msg.arg1);
System.out.println("msg:" + b.getString("name") + " - age:" + b.getInt("age"));
super.handleMessage(msg);
}
};
Message msg = handler.obtainMessage();
msg.arg1 = 121;
Bundle b = new Bundle();
b.putInt("age", 24);
b.putString("name", "Fatkun");
msg.setData(b);
msg.sendToTarget();
handler.post(r);
}
Runnable r = new Runnable() {
public void run() {
try {
// 在这里只是睡一下
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
HandlerThread使用方法:
//把上面创建Handler的代码
Handler handler = new Handler() {
...
}
//改为:
HandlerThread thread = new HandlerThread("athread");
thread.start(); //要把线程启动
Handler handler = new Handler(thread.getLooper()) {
...
}