首先看一下继承接口
从上面截图中可以看到他是个线程类,既然是线程类那么先看到run方法
@Override
public void run() {
mTid = Process.myTid();
//创建当前线程的Looper对象
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
//启动轮询
Looper.loop();
mTid = -1;
}
在run方法中主要就是创建Looper和启动looper的消息分发,看到了Looper那自然避不开Handler
/**
* @return a shared {@link Handler} associated with this thread
* @hide
*/
@NonNull
public Handler getThreadHandler() {
if (mHandler == null) {
mHandler = new Handler(getLooper());
}
return mHandler;
}
在HandlerThread中就有一个获取当前Handler的方法,这个方法被带上的hide注解我们在开发中无法自己调用需要新建handler传入Looper如下代码
val handlerThread = HandlerThread("handleThread")
handlerThread.start()
val looper = handlerThread.looper
Handler(looper).post {
Log.e(tag, "onCreate: ${Thread.currentThread().name}")
}
用这个Handler发送的消息就会在这个新建的线程中执行,这里有个则是通过HandlerThread#getLooper之前需要先调用线程的Thread#start让其先执行run方法不然会阻塞进入wait状态
public Looper getLooper() {
if (!isAlive()) {
return null;
}
boolean wasInterrupted = false;
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
//mLooper会在run方法中被创建
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
wasInterrupted = true;
}
}
}
/*
* We may need to restore the thread's interrupted flag, because it may
* have been cleared above since we eat InterruptedExceptions
*/
if (wasInterrupted) {
Thread.currentThread().interrupt();
}
return mLooper;
}
结合上面看到的源码总结出HandlerThread就是Thread+Handler是个适合执行耗时任务的Handler