Handler
在 Android
中负责发送和处理消息,通过它可以实现不同线程之间的消息通信。
每个 Handler
都需要绑定一个 Looper
来管理消息队列和消息循环。
Activity
被创建时就默认创建了 Looper
,所以在主线程中默认可以直接使用 Handler
。这时 Handler
绑定的是 Activity
的 Looper
。
当然也可以设置其他的 Looper
,如果没有指定 Looper
,默认使用 new Handler()
时线程所持有的 Looper
。
如果当前线程没有创建 Looper
,就会报错。
HandlerThread
HandlerThread
继承自 Thread
,本质就是个 Thread
。
其与普通 Thread
的区别在于实现了自己的 Looper
,可以单独分发和处理消息。
用来实现线程间的通信,主要是子线程和子线程间的通信。 Handler
更多的主要是子线程到主线程。
HandlerThread 的使用
有时候需要 Handler
收到消息时,在子线程处理消息。如果每次都通过 new Thread()
的方式来新开一个子线程,会浪费资源,增加系统开销。
Handler
可以指定 Looper
,但是需要自己处理 Looper
会比较麻烦,所以谷歌封装了 HandlerThread
类。
类似的类有 AsyncTask
。
HandlerThread
处理任务是串行执行,按消息发送顺序进行处理。
1. 创建
private HandlerThread mHandlerThread;
......
mHandlerThread = new HandlerThread("MyHandlerThread");
handlerThread.start();
HandlerThread
在调用 start()
方法之后,就可以获取到子线程的 Looper
。
2. Handler 中使用 mHandlerThread.getLooper()
mHandler = new Handler(mHandlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
System.out.println("收到消息 : " + Thread.currentThread());
}
};
给 mHandler
指定 mHandlerThread
线程中的 Looper
。
3. 在子线程使用 mHandler
发送消息,mHandler
中接收和处理消息(也是非 UI
线程)
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);//模拟耗时操作
System.out.println("发送消息 : " + Thread.currentThread());
mHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
4. 释放
@Override
protected void onDestroy() {
super.onDestroy();
if (mHandlerThread != null) {
mHandlerThread.quitSafely();
}
}
运行后的打印:
System.out: 发送消息 : Thread[Thread-7,5,main]
System.out: 收到消息 : Thread[MyHandlerThread,5,main]