HandlerThread使用场景:
本质就是Thread, 在run方法中执行了
Looper.prepare();
Looper.loop();
因此可以创建此线程内的Handler(mWorkHandler = new Handler(workThread.getLooper());)
应用场景,可以将mWorkHandler作为广播注册的参数,如:
mContext.registerReceiver(mReceiver, mFilter, null /* permission */, mWorkHandler);
这样广播接收者的onReceive方法就会在mWorkHandler的线程中执行。
另外在通过workThread.getLooper()获取Looper时候时使用了同步
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
wasInterrupted = true;
}
}
确保获取Looper时候不会为null。
注意:使用完后需要终止线程:mWorkThread.quit();