1 用法
HandlerThread thread = new HandlerThread("MyHandlerThread");
thread.start();
mHandler = new Handler(thread.getLooper());
mHandler.post(new Runnable(){...});
2 源码分析
public class HandlerThread extends Thread
HandlerThread 就是一个线程,只不过run方法里面封装了一个looper。先看看构造函数
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
HandlerThread 复写了Thread中的run方法,在run方法里面创建执行了looper轮询。并通过getLooper可以获得run方法里面的looper
public Looper getLooper() {
if (!isAlive()) {
return null;
}
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
并有退出方法quit
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
3 总结
HandlerThread就是一个线程,只是线程里面执行的是消息轮询。可以配合handler使用(将HandlerThread中的looper传入Handler构造函数中),让handler发送的消息在HandlerThread线程的looper中处理