HandlerThread是一個Android 已封裝好的輕量級異步類。HandlerThread本質上是一個線程類,它繼承了Thread;HandlerThread有自己的內部Looper對象,可以進行looper循環;通過獲取HandlerThread的looper對象傳遞給Handler對象,可以在handleMessage方法中執行異步任務。創建HandlerThread后必須先調用HandlerThread.start()方法,Thread會先調用run方法,創建Looper對象。
一、HandlerThread + Handler使用詳解
public class MainActivity extends AppCompatActivity {
private Handler mHandler;
private HandlerThread mHandlerThread;
private Handler uiHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 2:
//更新UI
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initHandlerThread();
//發送消息
mHandler.sendEmptyMessage(1);
}
private void initHandlerThread() {
//創建HandlerThread實例
mHandlerThread = new HandlerThread("handler_thread");
//開始運行線程
mHandlerThread.start();
//獲取HandlerThread線程中的Looper實例
Looper loop = mHandlerThread.getLooper();
//創建Handler與該線程綁定。
mHandler = new Handler(loop) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
Message message = new Message();
message.what = 2;
message.obj = "result";
uiHandler.sendMessage(message);
break;
default:
break;
}
}
};
}
@Override
protected void onDestroy() {
super.onDestroy();
//退出loop循環
mHandlerThread.quit();
}
}
一、HandlerThread源碼解析
(1)HandlerThread源碼
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;
}
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority;
}
@Override
public void run() {
mTid = Process.myTid();
//創建looper實例
Looper.prepare();
synchronized (this) {
//獲取當前線程的Looper實例
mLooper = Looper.myLooper();
//喚醒等待線程
notifyAll();
}
//設置線程優先級
Process.setThreadPriority(mPriority);
onLooperPrepared();
//開始循環
Looper.loop();
mTid = -1;
}
//返回與此線程關聯的Looper
public Looper getLooper() {
//先判斷當前線程是否啟動了
if (!isAlive()) {
return null;
}
//如果這個線程已經啟動,將會被阻塞,直到mLooper被初始化為止。
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
//等待喚醒
wait();
} catch (InterruptedException e) {
}
}
}
//在HandlerThread的run()方法中賦值的mLooper
return mLooper;
}
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
//quit方法會將消息隊列中的所有消息移除
looper.quit();
return true;
}
return false;
}
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
//quitSafely會將消息隊列所有的延遲消息移除,非延遲消息派發出去讓Handler去處理。
looper.quitSafely();
return true;
}
return false;
}
(2)Looper.prepare源碼
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
//判斷當前是否創建Looper實例,已經存在拋出異常
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//創建Looper實例
sThreadLocal.set(new Looper(quitAllowed));
}
Handler內存泄漏:主線程的Looper對象的生命周期 = 該應用程序的生命周期。在Java中,非靜態內部類 & 匿名內部類都默認持有外部類的引用
在Handler消息隊列還有未處理的消息 / 正在處理消息時,此時若需銷毀外部類MainActivity,但由于上述引用關系,垃圾回收器(GC)無法回收MainActivity,從而造成內存泄漏。
因為Looper的創建是在子線程中執行的,而調用getLooper方法則是在主線程進行的,這樣我們就無法保障我們在調用getLooper方法時Looper已經被創建。在獲取mLooper對象時會存在一個同步的問題,只有當線程創建成功并且Looper對象也創建成功之后才能獲得mLooper的值,HandlerThread內部則通過等待喚醒機制解決了同步問題。
從源碼可以看出當我們調用quit方法時,其內部實際上是調用Looper的quit方法而最終執行的則是MessageQueue中的removeAllMessagesLocked方法(Handler消息機制知識點),該方法主要是把MessageQueue消息池中所有的消息全部清空,無論是延遲消息(延遲消息是指通過sendMessageDelayed或通過postDelayed等方法發送)還是非延遲消息。
當調用quitSafely方法時,其內部調用的是Looper的quitSafely方法而最終執行的是MessageQueue中的removeAllFutureMessagesLocked方法,該方法只會清空MessageQueue消息池中所有的延遲消息,并將消息池中所有的非延遲消息派發出去讓Handler去處理完成后才停止Looper循環,quitSafely相比于quit方法安全的原因在于清空消息之前會派發所有的非延遲消息