前言
在Android開發(fā)過程中,使用Handler已經(jīng)是一件很平常的事了民逼。比如經(jīng)常遇到在子線程中如何更新UI胖替,AsyncTask的實(shí)現(xiàn),IntentService是如何實(shí)現(xiàn)在子線程工作的恋昼,當(dāng)碰到這些問題的時(shí)候,一下子就想到是Handler通過發(fā)送消息來實(shí)現(xiàn)的赶促。那么Handler是如何實(shí)現(xiàn)消息發(fā)送機(jī)制的呢液肌?
Handler工作流程
說到Handler,就要提起MessageQueue鸥滨,Looper嗦哆,Message。通常做法是在線程A中通過Handler發(fā)送一條消息Message到消息隊(duì)列MessageQueue婿滓,而Looper會(huì)在MessageQueue有消息到達(dá)時(shí)取出消息Message并且發(fā)送給Handler.dispatchMessage處理吝秕。它們之間的關(guān)系如下圖:
new Handler()
public Handler(@Nullable Callback callback, boolean async) {
// Looper.myLooper() => sThreadLocal.get()
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
通過創(chuàng)建Handler的源碼可以發(fā)現(xiàn),會(huì)先取Looper.myLooper()空幻,如果mLooper為空會(huì)拋出異常烁峭,看異常錯(cuò)誤可以得知是在當(dāng)前線程中沒有調(diào)用Looper.prepare()。那么為什么我們?cè)谥骶€程直接new Handler不會(huì)拋出異常呢秕铛?是因?yàn)閦ygote啟動(dòng)應(yīng)用進(jìn)程的時(shí)候约郁,在ActivityThread.main()中已經(jīng)給主線程創(chuàng)建了Looper,如下代碼所示:
public static void main(String[] args) {
// ...省略其他代碼
// 最終也是執(zhí)行Looper.prepare()
Looper.prepareMainLooper();
// ...省略其他代碼
//獲取的是H類的實(shí)例但两,H類也是繼承Handler
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
//開啟死循環(huán)
Looper.loop();
//一旦 Looper.loop() 執(zhí)行結(jié)束鬓梅,那么就拋出異常了
throw new RuntimeException("Main thread loop unexpectedly exited");
}
Looper.prepare()
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
首先會(huì)執(zhí)行sThreadLocal.get(),如果不為空則拋出異常谨湘,這里也解釋了為什么一個(gè)線程只能創(chuàng)建一個(gè)Looper的問題绽快;如果為空,則創(chuàng)建一個(gè)Looper設(shè)置給sThreadLocal紧阔,這樣就實(shí)現(xiàn)了Looper和ThreadLocal的雙向綁定坊罢。使用ThreadLocal就能達(dá)到線程間數(shù)據(jù)互不干擾的效果,這樣的設(shè)計(jì)也能避免線程間共享的數(shù)據(jù)不會(huì)錯(cuò)亂擅耽。接下來看下new Looper(quitAllowed)做了什么
new Looper(quitAllowed)
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
私有構(gòu)造函數(shù)也說明在創(chuàng)建Looper的時(shí)候是不允許通過new來創(chuàng)建的活孩,只能通過
Looper.prepare()來創(chuàng)建。在創(chuàng)建Looper的時(shí)候也創(chuàng)建了當(dāng)前線程的MessageQueue乖仇。接下來就是開始消息循環(huán)Looper.loop()
Looper.loop()
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
// ...省略代碼
for (;;) {
//從MessageQueue中取消息憾儒,沒有消息會(huì)阻塞,nativePollOnce
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// ...省略代碼
try {
// msg.target == handler
msg.target.dispatchMessage(msg);
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
// ...省略代碼
// 這里是回收msg的邏輯乃沙,提高性能和內(nèi)存
msg.recycleUnchecked();
}
}
首先還是判斷當(dāng)前線程是否有Looper,如果沒有拋出異常起趾,否則獲取當(dāng)前MessageQueue,通過死循環(huán)來調(diào)用MessageQueue的next方法獲取消息警儒,如果沒有消息則會(huì)阻塞训裆,阻塞是在MessageQueue.next方法中實(shí)現(xiàn),后面會(huì)分析。當(dāng)沒有獲取到消息的會(huì)直接退出循環(huán)缭保,這也是退出Looper的原因汛闸,而觸發(fā)的原因是調(diào)用了Looper.quit()間接的調(diào)用MessageQueue.quit()實(shí)現(xiàn)的。如果獲取到了消息艺骂,則調(diào)用msg.target.dispatchMessage(msg)來處理消息诸老,在MessageQueue.enqueueMessage給Message.target賦值為了當(dāng)前的Handler,這樣就能執(zhí)行到Handler.dispatchMessage中去了钳恕。所以也可以得到消息處理是在創(chuàng)建Handler所使用的Looper的線程中别伏,從而達(dá)到線程切換的目的。
MessageQueue的生產(chǎn)者enqueueMessage()
當(dāng)我們?cè)贖andler中發(fā)送消息時(shí)忧额,最終都會(huì)調(diào)用MessageQueue.enqueueMessage方法厘肮,使得消息入隊(duì)。
boolean enqueueMessage(Message msg, long when) {
//判斷msg必須得有Handler
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
//判斷當(dāng)前msg還沒有被處理過
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
//MessageQueue是生產(chǎn)者消費(fèi)者睦番,在next方法中同樣有synchronized (this) 类茂,這里是生產(chǎn)者
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
//如果msg是第一條消息或者執(zhí)行時(shí)間小于當(dāng)前第一條消息則放在鏈表第一條托嚣,并且將needWake置為mBlocked巩检,mBlocked是在next中賦值的,下面分析
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
//消息按照時(shí)間來插入到鏈表中
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// 如果需要喚醒示启,則調(diào)用nativeWake來喚醒被nativePollOnce掛起的線程
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
MessageQueue是一種生產(chǎn)者消費(fèi)者模式兢哭,enqueueMessage方法內(nèi)部用synchronized (this)獲取當(dāng)前對(duì)象的鎖,將msg按照?qǐng)?zhí)行的時(shí)間順序添加到MessageQueue中夫嗓,如果當(dāng)前線程是被掛起的狀態(tài)迟螺,還要通過nativeWake來喚醒線程。
MessageQueue的消費(fèi)者next()
從前面我們可以知道舍咖,在Looper.loop()開啟死循環(huán)后矩父,就在等待MessageQueue.next()返回可以處理的消息。
Message next() {
//如果消息隊(duì)列已經(jīng)退出了谎仲,則就返回null浙垫,那么在looper.loop()就會(huì)得null的message,從而退出
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
//掛起當(dāng)前線程郑诺,native中通過epoll_wait()來阻塞的
nativePollOnce(ptr, nextPollTimeoutMillis);
//這里的 synchronized (this)是消費(fèi)者
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
//mQuitting是quit()函數(shù)賦值的,如果mQuitting為true表示消息隊(duì)列要退出了杉武,返回msg=null辙诞;
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
//如果msg==null時(shí),nextPollTimeoutMillis = -1轻抱,之所以nextPollTimeoutMillis沒有執(zhí)行循環(huán)末尾的重新賦值為0飞涂,就是因?yàn)檫@里需要執(zhí)行空閑時(shí)的IdleHandler個(gè)數(shù)為0,continue后,執(zhí)行nativePollOnce進(jìn)入了阻塞
if (pendingIdleHandlerCount <= 0) {
//阻塞掛起较店,并且賦值 mBlocked為true士八,那么下次有消息時(shí),在enqueueMessage方法中就要喚醒被掛起的線程
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
首先判斷消息隊(duì)列是否退出梁呈,如果退出則直接返回null給Looper退出婚度,沒有退出則繼續(xù)執(zhí)行。nativePollOnce(ptr, nextPollTimeoutMillis)是通過nextPollTimeoutMillis來說明當(dāng)前是否需要掛起和掛起時(shí)間官卡。當(dāng)nextPollTimeoutMillis==-1時(shí)表示一直阻塞不會(huì)超時(shí)蝗茁;當(dāng)nextPollTimeoutMillis==0時(shí)表示不會(huì)阻塞立即返回;當(dāng)nextPollTimeoutMillis>0時(shí)表示當(dāng)前線程最長需要掛起多長時(shí)間寻咒。局部變量nextPollTimeoutMillis初始值為0哮翘,進(jìn)入同步代碼塊后,如果獲取到當(dāng)前msg為空毛秘,則nextPollTimeoutMillis=-1饭寺,我們可以發(fā)現(xiàn)在循環(huán)末尾會(huì)重新給nextPollTimeoutMillis賦值為0,那么nativePollOnce就不會(huì)阻塞掛起了叫挟。但其實(shí)還要注意到pendingIdleHandlerCount這個(gè)空閑時(shí)可處理的IdleHandler個(gè)數(shù)艰匙,如果沒有添加的IdleHandler那么就是0,所以這里執(zhí)行continue后霞揉,繼續(xù)for循環(huán)nativePollOnce(ptr,-1)阻塞掛起了旬薯。如果msg!=null的時(shí)候,就會(huì)比較當(dāng)前時(shí)間是否小于消息執(zhí)行的時(shí)間适秩,如果小于的話绊序,線程就會(huì)進(jìn)入最長需要掛起的時(shí)間;如果大于就返回當(dāng)前的msg秽荞。
執(zhí)行工作的Handler.dispatchMessage()
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
如果msg的callback不為空骤公,就執(zhí)行msg的callback.run(),如果調(diào)用Handler.post系列的方法扬跋。如果msg.callback為空阶捆,則判斷Callback是否為空,不為空就執(zhí)行mCallback的handleMessage方法钦听,最后才執(zhí)行Handler的handleMessage洒试,這也是平常用的最多的。
Message.recycleUnchecked()
在Looper.loop()執(zhí)行完msg.target.dispatchMessage(msg)后朴上,還會(huì)執(zhí)行msg.recycleUnchecked()垒棋。
void recycleUnchecked() {
// ...省略初始化代碼
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
如果當(dāng)前sPoolSize還沒有到MAX_POOL_SIZE(50個(gè)),就把當(dāng)前的msg放入隊(duì)列的頭部痪宰。這種方式相比于new Message()叼架,可以提升內(nèi)存的使用率畔裕,如果一直new實(shí)例,則在內(nèi)存空間上就會(huì)出現(xiàn)很多碎片乖订,也可能造成頻繁gc扮饶。所以推薦使用Handler.obtainMessage()
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
Looper.quit()和quitSafely()
如果在子線程中創(chuàng)建了Looper,就可以通過quit或者quitSafely來退出消息隊(duì)列乍构。這樣可以停止線程的Looper.loop()甜无,并且不會(huì)有內(nèi)存泄漏問題。quit和quitSafely的區(qū)別就是蜡吧,quit會(huì)移除所有的消息毫蚓,quitSafely只會(huì)移除還沒處理的消息。
至此昔善,就明白Android中Handler的工作原理元潘,再去看AsyncTask,IntentService,HandlerThread就比較容易理解了。
總結(jié):
1.使用handler之前必須先調(diào)用Looper.prepare來創(chuàng)建Looper君仆,否則會(huì)報(bào)異常翩概。所以在子線程需要執(zhí)行Looper.prepare(),通過Looper.myLooper()來獲取當(dāng)前線程的Looper返咱,一個(gè)線程只有一個(gè)Looper和MessageQueue钥庇。主線程不用執(zhí)行是因?yàn)樵贏ctivityThread.main中已經(jīng)執(zhí)行了Looper.prepareMainLooper()
2.處理Handler消息的線程是Looper所在的線程,所以在IntentService中雖然在主線程中創(chuàng)建的ServiceHandler,但是Looper是HandlerThread中的子線程Looper,所以在處理消息onHandleIntent()時(shí)是在子線程處理的咖摹,可以做耗時(shí)操作
3.MessageQueue消息隊(duì)列是生產(chǎn)者消費(fèi)者模式评姨,在添加消息是按照?qǐng)?zhí)行的時(shí)間when順序插入到鏈表中去的。
4.Looper.loop()死循環(huán)不會(huì)導(dǎo)致ANR萤晴,因?yàn)樵跊]有消息時(shí)會(huì)阻塞并且掛起當(dāng)前線程吐句,而不會(huì)超時(shí),只有超時(shí)沒有響應(yīng)才會(huì)導(dǎo)致ANR店读。當(dāng)MessageQueue沒有消息時(shí)嗦枢,會(huì)調(diào)用nativePollOnce導(dǎo)致線程阻塞,直到有消息到達(dá)時(shí)調(diào)用nativeWake來喚醒線程屯断。
5.如果需要退出Looper文虏,可以調(diào)用Looper.quit()或者quitSafely(),但是主線程是不能退出的殖演,因?yàn)橹骶€程在mQuitAllowed為false氧秘,調(diào)用quit會(huì)直接異常。
6.在使用Message時(shí)趴久,最好使用Handler.obtainMessage來取代new Message()
7.Handler引起內(nèi)存泄漏的原因敏储,在發(fā)送消息的時(shí)候msg會(huì)引用Hanlder作為target成員變量的值。在子線程中沒有釋放Looper對(duì)象朋鞍。