前言:
對于一個Android研發(fā)而言剿骨,親身體會就是不管在平時開發(fā)或者面試的時候,Handler消息機(jī)制毋庸置疑都是一個必備的知識點埠褪,所以這邊留一份個人筆記,如有分析不對的地方挤庇,還望指出钞速!
目錄:
1、如何分析Handler源碼
2嫡秕、源碼大致流程:消息的入隊與出隊
3渴语、從大致流程進(jìn)入細(xì)化分析
3.1、Handler昆咽、Looper驾凶、MessageQueue三者之間的關(guān)系
3.2牙甫、Handler、Looper调违、MessageQueue之間的協(xié)作
總結(jié)圖1:Handler在子線程中發(fā)送消息窟哺,消息會被添加到MessageQueue消息隊列中,再來由Handler所處的當(dāng)前線程的Looper來不斷的輪詢MessageQueue以獲取出隊消息技肩,最后調(diào)用dispatchMessage進(jìn)行消息傳遞給handleMessage進(jìn)行處理:
1且轨、如何分析源碼
眾所皆知的Android源碼的有很多,涉及到一個類或者多個類虚婿,一個類中又有很多代碼旋奢,所以這邊最簡單的分析方式就是回歸到Handler的使用中來,也就是如何使用Handler
1.1然痊、實例一個Handler對象(主線程)
1.2至朗、在子線程中使用Handler發(fā)送一個消息,如:handler.sendEmptyMessage(1)
1.3剧浸、消息發(fā)送出之后(執(zhí)行1.2步驟)锹引,消息最終會被轉(zhuǎn)發(fā)到我們new出來的Handler中的handleMessage方法進(jìn)行處理(子線程消息發(fā)送到主線程中處理)
以上3個步驟即為我們對Handler的基本使用方式,所以辛蚊,我們可以以發(fā)送消息的時機(jī)粤蝎,作為源碼分析的切入點,并留下一個疑問:
問題1:子線程發(fā)送的消息為什么是在主線程中接收的呢袋马?
2初澎、源碼大致流程:消息的入隊與出隊
2.1、消息發(fā)送:sendMessage(Message msg) \ sendEmptyMessage(int what) \ postDelayed(Runnable r, long delayMillis) 等等
2.2虑凛、消息及發(fā)送時間處理:sendMessageAtTime(Message msg, long uptimeMillis)
2.3碑宴、消息隊列添加:enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)
2.4、消息出隊:到這里桑谍,既然有消息添加到隊列中的流程延柠,而且我們最終都會獲得相應(yīng)的消息返回,那么消息是如何出隊的呢锣披?帶著這個疑問贞间,我們最終在MessageQueue 消息隊列中找到一個函數(shù)名稱為 next() 的函數(shù)。
問題2:這個next()函數(shù) 是在什么時候調(diào)用的呢雹仿?
在Handler源碼上增热,以消息發(fā)送作為分析切入點來查看,如2.1羅列的幾種消息發(fā)送方式胧辽,我們都可以很清楚的發(fā)現(xiàn)峻仇,消息都是調(diào)用了sendMessageDelayed(Message msg, long delayMillis),最終調(diào)用到sendMessageAtTime(Message msg, long uptimeMillis)邑商,然后在該方法里面調(diào)用了enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)摄咆,到這里凡蚜,不管從方法名稱還是局部變量的名稱來看,這邊都出現(xiàn)了一個隊列的信息吭从,所以可以知道Handler的消息發(fā)送最終是在sendMessageAtTime里面調(diào)用了MessageQueue.enqueueMessage()對消息進(jìn)行隊列添加朝蜘,然后調(diào)用了MessageQueue.next()進(jìn)行消息輪詢并返回Message結(jié)果。
3影锈、從大致流程進(jìn)入細(xì)化分析
3.1芹务、Handler、Looper鸭廷、MessageQueue三者之間的 關(guān)系圖2 如下:
在分析到第2步的sendMessageAtTime結(jié)束時枣抱,我們這邊引出了一個消息隊列的內(nèi)容:MessageQueue queue = mQueue
/**
* Enqueue a message at the front of the message queue, to be processed on
* the next iteration of the message loop. You will receive it in
* {@link #handleMessage}, in the thread attached to this handler.
* <b>This method is only for use in very special circumstances -- it
* can easily starve the message queue, cause ordering problems, or have
* other unexpected side-effects.</b>
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean sendMessageAtFrontOfQueue(Message msg) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, 0);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
問題:mQueue是什么東西?這個mQueue是怎么來的辆床?所以我們在Handler的構(gòu)造方法中找到了它的初始化位置
/**
* Use the {@link Looper} for the current thread with the specified callback interface
* and set whether the handler should be asynchronous.
*
* Handlers are synchronous by default unless this constructor is used to make
* one that is strictly asynchronous.
*
* Asynchronous messages represent interrupts or events that do not require global ordering
* with respect to synchronous messages. Asynchronous messages are not subject to
* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
*
* @param callback The callback interface in which to handle messages, or null.
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*
* @hide
*/
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
到此佳晶,從上面的兩段源碼,且?guī)е?點中讼载,next()被調(diào)用的時機(jī)問題轿秧,我們引出了os/Handler中的兩個成員變量
final Looper mLooper;
final MessageQueue mQueue;
MessageQueue 對象是從Looper中獲得的,也就是說mQueue是在Looper中實例化的咨堤,所以很明顯菇篡,Handler中的消息隊列MessageQueue 是從輪詢器Looper中獲得的。
那么問題來了:為什么消息隊列要在輪詢器中進(jìn)行實例化一喘,請看以下源碼
/**
* Return the {@link MessageQueue} object associated with the current
* thread. This must be called from a thread running a Looper, or a
* NullPointerException will be thrown.
*/
public static @NonNull MessageQueue myQueue() {
return myLooper().mQueue;
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
MessageQueue在Looper中進(jìn)行實例化驱还,也就是說一個Looper就有一個MessageQueue,屬于綁定關(guān)系凸克,從而得出一個Looper只能輪詢一個消息隊列
所以可得出如關(guān)系圖2中Handler议蟆、Looper、MessageQueue三者的關(guān)系:Handler中持有Looper和MessageQueue萎战,Looper中持有MessageQueue咐容,而且Handler中的MessageQueue來自于Looper中的MessageQueue。
Handler是使用時通過New實例化出來的蚂维,MessageQueue是在Looper中進(jìn)行實例的戳粒,那么這個Looper是如何實例化的?所以這邊我們將引出 ActivityThread虫啥。而ActivityThread是什么東西呢享郊?這邊就稍微介紹一下:
安卓應(yīng)用程序作為一個控制類程序,跟Java程序類似孝鹊,都是有一個入口的,而這個入口就是ActivityThread的main函數(shù):
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
以上的main函數(shù)代碼中展蒂,我們還需要意識到兩個問題:
1.我們之所以可以在Activity用Handler handler=new Handler()直接創(chuàng)建出來就默認(rèn)綁定到主線程了又活,是因為上面的代碼為我們做了綁定主線程的Looper的事情苔咪,
2.主線程的Looper是不能在程序中調(diào)用退出的,最后一句代碼看到?jīng)]柳骄,如果調(diào)用的話团赏,就會拋出異常,退出主線程的循環(huán)是框架層在調(diào)用退出應(yīng)用程序的時候才調(diào)用的
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
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));
}
在ActivityThread的main中調(diào)用了 Looper.prepareMainLooper() -> prepare(false) -> sThreadLocal.set(new Looper(quitAllowed))耐薯, 這么一來舔清,是不是執(zhí)行到了上面的Looper構(gòu)造函數(shù)中了?到這里曲初,細(xì)心的人會發(fā)現(xiàn)這么一個問題:
問題3:Looper被實例化出來之后并沒有直接返回体谒,而是被set到了ThreadLocal中?
Handler與Looper是成對出現(xiàn)的臼婆,一個子線程發(fā)送消息抒痒,一個主線程接收消息,那么這邊就涉及到了多線程颁褂,線程之間的通訊故响,是需要保證數(shù)據(jù)的安全,即數(shù)據(jù)隔離颁独,所以使用到了ThreadLocal進(jìn)行線程管理:如A線程在獲取數(shù)據(jù)時只能獲取A線程所控制的數(shù)據(jù)彩届,而不能去獲取到B線程中對應(yīng)的數(shù)據(jù),否則就會引起數(shù)據(jù)不同步誓酒,比如A線程數(shù)據(jù)被B線程數(shù)據(jù)所覆蓋之類的問題樟蠕,同時也驗證了一個線程只能關(guān)聯(lián)一個Looper對象。
所以問題3解決了丰捷。最后這個main的結(jié)尾坯墨,調(diào)用了 Looper.loop(); 進(jìn)行輪詢消息隊列! 是不是很完美了病往?
3.2捣染、Handler、Looper停巷、MessageQueue之間的協(xié)作
通過前面的源碼分析耍攘,我們已經(jīng)知道了消息是如果添加到消息隊列了。我們再來看消息的出隊分析畔勤。
以下在Looper輪詢器中的loop()中我們看到這樣一句代碼:Message msg = queue.next(); // might block
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the 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;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycleUnchecked();
}
}
所以通過以上代碼蕾各,我們可以知道消息的出隊,是在Looper這個輪詢器中的loop()函數(shù)通過死循環(huán)的方式:for (;;)庆揪,不斷的通過隊列的next()方法中拿到消息:queue.next()式曲,并且如果隊列消息為null了,就跳出該輪詢。所以問題2是不是已經(jīng)解決了吝羞?
在出隊過程中兰伤,也就是MessageQueue消息隊列中的next()函數(shù)中,我們可以知道next()返回的是一個Message消息對象钧排,從函數(shù)注釋上來看:當(dāng)輪詢器 loop 輪詢的時候會返回一條消息敦腔,且從代碼for (;;)循環(huán)的代碼中可以看出,是在這里不斷的拿到消息隊列并返回下一條消息,到這里,我們需要注意的是因為這個消息是可以循環(huán)使用的峻呛,而且我們可以看到這樣一個native函數(shù)調(diào)用:nativePollOnce(ptr, nextPollTimeoutMillis);所以我們可以得出消息的循環(huán)使用內(nèi)存是通過C++來維護(hù)完成的(這邊因為對native沒有深入研究,所以pass這塊判族!)
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
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();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
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) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
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;
}
// Process the quit message now that all pending messages have been handled.
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();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
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;
}
}
到這邊,如果所有的分析及源碼查看都看懂的話系吭,我們就已經(jīng)掌握了在整個Handler消息機(jī)制中五嫂,是如何從一個消息的發(fā)送,進(jìn)行了怎么樣的世界環(huán)游肯尺,最終如何回到了Handler的handleMessage中的沃缘!
分析到這里為止,如果還沒蒙圈的人會發(fā)現(xiàn)则吟,我們在前面提出過的幾個問題都解決了槐臀,那么問題1呢?
子線程發(fā)送的消息為什么是在主線程中接收的呢氓仲?
其實我們在前面也已經(jīng)有提及到了該問題水慨,就是為什么在ActivityThread的main中實例化的Looper對象是被set到了ThreadLocal中。
在java中敬扛,main是不是主線程呢晰洒?不需要解釋了吧∩都看代碼:當(dāng)前線程中Looper的獲取方式
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
程序一開始在ActivityThread在執(zhí)行main函數(shù)時實例化Looper谍珊,然后保存到了ThreadLocal中。而我們在主線程中new了一個Handler急侥,那么Handler默認(rèn)對應(yīng)的Looper就是主線程的Looper:通過以上代碼砌滞,從ThreadLocal管理中獲取出當(dāng)前線程(主線程)對應(yīng)的Looper對象,所以對應(yīng)的Looper自然也是主線程的Looper坏怪,明白了嗎贝润?
所以主線程的Looper在輪詢出消息隊列MessageQueue中的消息時,就是出于主線程中铝宵,這樣問題1是不是就清楚了打掘。