如何使用HandlerThread?
HandlerThread本質(zhì)上是一個(gè)線程類,繼承自Thread類,但是HandlerThread有自己的Looper對象,可以進(jìn)行l(wèi)ooper循環(huán),不斷從MessageQueue中取消息。那么,我們?nèi)绾问褂肏andlerThread呢?
- 創(chuàng)建HandlerThread實(shí)例
// 創(chuàng)建HandlerThread的實(shí)例,并傳入?yún)?shù)來表示當(dāng)前線程的名字,此處//將該線程命名為“HandlerThread”
private HandlerThread mHandlerThread = new HandlerThread("HandlerThread");
- 啟動HandlerThread線程
mHandlerThread.start();
- 使用HandlerThread的Looper去構(gòu)建Handler并實(shí)現(xiàn)其handlMessage的回調(diào)方法
private Handler mHandler;
// 該Callback方法運(yùn)行于子線程,mHandler在創(chuàng)建時(shí)使用的是mHandlerThread的looper對象!!
mHandler = new Handler(mHandlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d("Kathy","Received Message = " + msg.what + " CurrentThread = " + Thread
.currentThread().getName());
}
};
可以看出,我們將前面的創(chuàng)建的HandlerThread實(shí)例的Looper對象傳遞給了Handler,這使得該Handler擁有了HandlerThread的Looper對象,通過該Handler發(fā)送的消息,都將被發(fā)送到該Looper對象的MessageQueue中,且回調(diào)方法的執(zhí)行也是執(zhí)行在HandlerThread這個(gè)異步線程中。
值得注意的是,如果在handleMessage()執(zhí)行完成后,如果想要更新UI,可以用UI線程的Handler發(fā)消息給UI線程來更新。
舉個(gè)Simple的例子
請看以下代碼:
/**
* Created by Kathy on 17-2-21.
*/
public class HandlerThreadActivity extends Activity {
private HandlerThread mHandlerThread;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 創(chuàng)建HandlerThread實(shí)例并啟動線程執(zhí)行
mHandlerThread = new HandlerThread("HandlerThread");
mHandlerThread.start();
// 將mHandlerThread.getLooper()的Looper對象傳給mHandler,之后mHandler發(fā)送的消息都將在
// mHandlerThread這個(gè)線程中執(zhí)行
mHandler = new Handler(mHandlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d("Kathy","Received Message = " + msg.what + " CurrentThread = " + Thread
.currentThread().getName());
}
};
//在主線程中發(fā)送一條消息
mHandler.sendEmptyMessage(1);
new Thread(new Runnable() {
@Override
public void run() {
//在子線程中發(fā)送一條消息
mHandler.sendEmptyMessage(2);
}
}).start();
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandlerThread.quit();
}
}
創(chuàng)建mHandler時(shí)傳入HandlerThread實(shí)例的Looper對象,然后分別在主線程和其他的子線程中發(fā)送空消息,猜測handleMessage()中的Log會輸出什么?
執(zhí)行結(jié)果如下:
02-21 19:37:30.395 19479-19506/? D/Kathy: Received Message = 1 CurrentThread = HandlerThread
02-21 19:37:30.396 19479-19506/? D/Kathy: Received Message = 2 CurrentThread = HandlerThread
可知,無論是在主線程中發(fā)送消息,還是在其他子線程中發(fā)送消息,handleMessage()方法都在HandlerThread中執(zhí)行。
源碼角度解析HandlerThread
HandlerThread的源碼結(jié)構(gòu)很簡單,行數(shù)也不多,推薦大家自己去SDK中閱讀。
HandlerThread有兩個(gè)構(gòu)造函數(shù),在創(chuàng)建時(shí)可以根據(jù)需求傳入兩個(gè)參數(shù):線程名稱和線程優(yōu)先級。代碼如下:
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;
}
在HandlerThread對象的start()方法調(diào)用之后,線程被啟動,會執(zhí)行到run()方法,接下來看看,HandlerThread的run()方法都做了什么事情?
/**
* 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;
}
在run()方法中,執(zhí)行了Looper.prepare()方法,mLooper保存并獲得了當(dāng)前線程的Looper對象,并通過notifyAll()方法去喚醒等待線程,最后執(zhí)行了Looper.loop()開啟looper循環(huán)語句。也就是說,run()方法的主要作用就是完成looper機(jī)制的創(chuàng)建。Handler可以獲得這個(gè)looper對象,并開始異步消息傳遞了。
接下來看看Handler是如何獲得這個(gè)Looper對象呢?
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason is 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;
}
Handler通過getLooper()方法獲取looper對象。該方法首先判斷當(dāng)前線程是否啟動?如果沒有啟動,返回null;如果啟動,進(jìn)入同步語句。如果mLooper為null,代表mLooper沒有被賦值,則當(dāng)前調(diào)用線程進(jìn)入等待階段。直到Looper對象被創(chuàng)建且通過notifyAll()方法喚醒等待線程,最后才會返回Looper對象。我們看到在run()方法中,mLooper在得到Looper對象后,會發(fā)送notifyAll()方法來喚醒等待的線程。
Looper對象的創(chuàng)建在子線程的run()方法中執(zhí)行,但是調(diào)用getLooper()的地方是在主線程中運(yùn)行,我們無法保證在調(diào)用getLooper()時(shí)Looper已經(jīng)被成功創(chuàng)建,所以會在getLooper()中存在一個(gè)同步的問題,通過等待喚醒機(jī)制解決了同步的問題。
那么,HandlerThread是如何退出的呢?
/**
* Quits the handler thread's looper.
* <p>
* Causes the handler thread's looper to terminate without processing any
* more messages in the message queue.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p class="note">
* Using this method may be unsafe because some messages may not be delivered
* before the looper terminates. Consider using {@link #quitSafely} instead to ensure
* that all pending work is completed in an orderly manner.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*
* @see #quitSafely
*/
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
/**
* Quits the handler thread's looper safely.
* <p>
* Causes the handler thread's looper to terminate as soon as all remaining messages
* in the message queue that are already due to be delivered have been handled.
* Pending delayed messages with due times in the future will not be delivered.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p>
* If the thread has not been started or has finished (that is if
* {@link #getLooper} returns null), then false is returned.
* Otherwise the looper is asked to quit and true is returned.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*/
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
looper.quitSafely();
return true;
}
return false;
}
向下調(diào)用到Looper的quit()方法
public void quit() {
mQueue.quit(false);
}
public void quitSafely() {
mQueue.quit(true);
}
再向下調(diào)用到MessageQueue的quit()方法:
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
可以看到,無論是調(diào)用quit()方法還是quitSafely(),最終都將執(zhí)行到MessageQueue中的quit()方法。
quit()方法最終執(zhí)行的removeAllMessagesLocked()方法,該方法主要是把MessageQueue消息池中所有的消息全部清空,無論是延遲消息(延遲消息是指通過sendMessageDelayed或通過postDelayed等方法發(fā)送)還是非延遲消息。
quitSafely()方法,其最終執(zhí)行的是MessageQueue中的removeAllFutureMessagesLocked方法,該方法只會清空MessageQueue消息池中所有的延遲消息,并將消息池中所有的非延遲消息派發(fā)出去讓Handler去處理完成后才停止Looper循環(huán),quitSafely相比于quit方法安全的原因在于清空消息之前會派發(fā)所有的非延遲消息。最后需要注意的是Looper的quit方法是基于API 1,而Looper的quitSafely方法則是基于API 18的。