一、HandlerThread是什么
用于防止Looper拿到空指针,下面让我们来看看,它是如何操作的吧
1.Looper getLooper()方法
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;
}
2.handlerThread.run()方法
public void run() {
mTid = Process.myTid();
Looper.prepare();//创建一个Looper对象
synchronized (this) {
mLooper = Looper.myLooper();//把Looper对象复制给MyLooper
notifyAll();//通知notify方法,MyLooper就能唤醒在等待当前线程的对象,Handler就能拿到对象,则不会报出空指针问题
}//线程同步之间的判断
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
二、总结
总结: 因此在开发中,可以用handlerThread去模拟一个异步任务的一种操作,只需在主线程中给子线程发送消息,让子线程去处理一些耗时的操作(例如:下载网络图片、更新数据库)只要在handlerThread‘中去创建一个Looper,再与一个默认的Handler进行关联,所有的handleMessage方法都是在子线程中去调用。在设计时,可以减轻考虑开启几个线程,开启线程之后,再异步任务中添加要执行的任务(要考虑存储结构),什么时候添加、移除、传递开发的负担。