public class HandlerThread extends Thread {
int mPriority;
int mTid = -1;
Looper mLooper;
private @Nullable Handler mHandler;
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
/**
* Constructs a HandlerThread.
* @param name
* @param priority The priority to run the thread at. The value supplied must be from
* {@link android.os.Process} and not from java.lang.Thread.
*/
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority;
}
/**
* Call back method that can be explicitly overridden if needed to execute some
* setup before Looper loops.
*/
protected void onLooperPrepared() {
}
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason isAlive() returns false, this method will return null. If this thread
* has been started, this method will block until the looper has been initialized.
* @return The 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;
}
/**
* @return a shared {@link Handler} associated with this thread
* @hide
*/
@NonNull
public Handler getThreadHandler() {
if (mHandler == null) {
mHandler = new Handler(getLooper());
}
return mHandler;
}
关键的就是这些,很明显的可以看出,handlerThread在一个子线程里面封装好了looper和handler,所以这就是为什么在子线程里面使用handlerThread直接run就可以了。
在getLooper里面,handlerThread对线程是否存在加了一个判断,因为handler在主线程,而handlerThread创建的Looper在子线程,如果子线程没有创建或者子线程的Looper没有创建,那handler也不知道给谁发消息。所以这里handlerThread加了一层判断,确保子线程的Looper创建。
关于handlerThread的使用场景,一般就是在子线程中使用,因为如果按照正常的handler使用的话,需要自己额外在子线程新建一个Looper(由于主线程已经默认有一个Looper了,所以在主线程可以直接用handler)。例如在子线程不断地获取数据更新UI的时候,就可以用到handlerThread。