一 前言
對于Android開發(fā)者來說,在日常開發(fā)過程中不可避免會(huì)涉及到Android中的消息機(jī)制的場景應(yīng)用咧纠,比如在子線程進(jìn)行一些耗時(shí)操作瞬内,操作完成后需要在主線程更新UI,該場景想必大家都在實(shí)際開發(fā)過程中遇到過碘勉。另外,看過Android源碼的開發(fā)者想必也知道桩卵,多處Android源碼中也使用到消息機(jī)制進(jìn)行通信验靡,比如,Activity雏节、Service的啟動(dòng)過程就都涉及到胜嗓。因此,本文從源碼層面分析Android中消息機(jī)制的工作原理钩乍。而要理解Android的消息機(jī)制的運(yùn)行機(jī)制辞州,需要從Looper , Handler , Message等工作原理進(jìn)分析。下面先寫一個(gè)使用示例寥粹,然后根據(jù)該示例進(jìn)行源碼跟蹤变过。
二 示例展示
public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
private Handler mainHandler;
private Handler threadHandler;
/**
* 在主線程中創(chuàng)建Handler,并實(shí)現(xiàn)對應(yīng)的handleMessage方法
*/
public static Handler mainHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.i(TAG, "主線程中接收到handler消息...")
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//子線程中創(chuàng)建handler
new Thread(new Runnable() {
@Override
public void run() {
threadHandler = new Handler();
}
}).start();
}
此時(shí)運(yùn)行程序涝涤,你會(huì)發(fā)現(xiàn)媚狰,在子線程中創(chuàng)建的Handler是會(huì)導(dǎo)致程序崩潰的,提示的錯(cuò)誤信息為 Can't create handler inside thread that has not called Looper.prepare() 阔拳。如何解決該問題崭孤,其實(shí)只需按提示信息所述,在當(dāng)前線程中調(diào)用Looper.prepare(),即為當(dāng)前線程創(chuàng)建了Looper辨宠。代碼如下:
//子線程中創(chuàng)建handler
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
threadHandler = new Handler();
Looper.loop();
}
}).start();
另外遗锣,通過查看下Handler的源碼,也可以弄清楚為什么不調(diào)用Looper.prepare()就crash彭羹。Handler的構(gòu)造函數(shù)如下所示:
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;
}
可知黄伊,上述代碼塊中泪酱,調(diào)用了Looper.myLooper();語句派殷,然后賦值給一個(gè)Looper對象mLooper ,如果mLooper實(shí)例為空墓阀,則會(huì)拋出一個(gè)運(yùn)行時(shí)異常(Can’t create handler inside thread that has not called Looper.prepare()U毕А)。
這里調(diào)用了Looper.myLooper()斯撮,那么我們接下來通過它來了解Looper的工作原理经伙。
三 源碼分析
接著上一小節(jié)分析,查看myLooper()方法的代碼:
public static final Looper myLooper() {
return (Looper)sThreadLocal.get();
}
方法就是從sThreadLocal對象中取出Looper勿锅。如果sThreadLocal中有Looper存在就返回Looper帕膜,如果沒有Looper存在自然就返回空了。因此溢十,源碼中肯定在某處給sThreadLocal設(shè)置Looper垮刹?顯然是的,并且是在Looper.prepare()方法中進(jìn)行設(shè)置张弛,接著來看下它的源碼:
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));
}
代碼中首先判斷sThreadLocal中是否已經(jīng)存在Looper了荒典,如果還沒有則創(chuàng)建一個(gè)新的Looper設(shè)置進(jìn)去。如果有也會(huì)拋出異常吞鸭,即要求每個(gè)線程中最多有且只有一個(gè)Looper對象寺董。其中,sThreadLocal是ThreadLocal的實(shí)例刻剥,后面會(huì)再專門介紹ThreadLocal遮咖,當(dāng)前只要知道ThreadLocal的作用是要可以在每個(gè)線程中存儲數(shù)據(jù),并且不同線程中互不干擾造虏。接著看Looper的構(gòu)造函數(shù)源碼:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在Looper構(gòu)造函數(shù)創(chuàng)建了一個(gè)MessageQueue和獲取當(dāng)前Thread實(shí)例引用盯滚。MessageQueue是消息隊(duì)列,即用于存儲消息酗电,以及以隊(duì)列的形式對外提供入隊(duì)及出隊(duì)操作魄藕,后面再通過源碼再分析。
通過以上子線程創(chuàng)建Handle的過程分析可知撵术,子線程中需要先調(diào)用Looper.prepare()才能創(chuàng)建Handler對象背率。那么示例展示的主線程中mainHandler創(chuàng)建為何不崩潰呢?其原因是在程序啟動(dòng)的時(shí)候,系統(tǒng)已經(jīng)幫我們自動(dòng)調(diào)用了Looper.prepare()方法寝姿。我們可以查看ActivityThread中的main()方法交排,代碼如下所示:
public static void main(String[] args) {
SamplingProfilerIntegration.start();
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
EventLogger.setReporter(new EventLoggingReporter());
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
if (false) {
Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
用了Looper.prepareMainLooper()方法,而這個(gè)方法又會(huì)再去調(diào)用Looper.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();
}
}
可知埃篓,ActivityThread被創(chuàng)建時(shí)變會(huì)初始化Looper,從而不需要再手動(dòng)去調(diào)用Looper.prepare()方法了根资。
此外架专,ActivityThread中的main()方法中最后調(diào)用了 Looper.loop(),它是Looper中一個(gè)重要方法玄帕,只有調(diào)用了loop后消息循環(huán)系統(tǒng)才會(huì)真正的起作用部脚,它的源碼實(shí)現(xiàn)如下:
/**
* 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();
}
}
這個(gè)方法進(jìn)入了一個(gè)死循環(huán),然后不斷地調(diào)用的MessageQueue的next()方法裤纹,MessageQueue的next()方法即是出隊(duì)方法委刘,源碼如下:
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;
}
}
方法中判斷當(dāng)前MessageQueue中如果存在mMessages(即待處理消息),就將這個(gè)消息出隊(duì)鹰椒,然后讓下一條消息成為mMessages锡移,否則就進(jìn)入一個(gè)阻塞狀態(tài),一直等到有新的消息入隊(duì)漆际。
回到Looper類的loop()方法淆珊,如果next()方法返回的msg等于null,就退出該循環(huán)灿椅,否則每當(dāng)有一個(gè)消息出隊(duì)套蒂,接著就將它傳遞到msg.target的dispatchMessage()方法中,那這里msg.target又是什么呢茫蛹?其實(shí)就是Handler啦操刀,也就是回調(diào)到Handler進(jìn)行處理消息,那么如何處理呢婴洼?在介紹由Handler的dispatchMessage()方法進(jìn)行處理消息之前骨坑,我們首先得知道如何向MessageQueue中插入消息,即Handler如何發(fā)送消息柬采?示例代碼如下:
new Thread() {
@Override
public void run() {
// 在子線程中發(fā)送異步消息
Message message = new Message();
message.arg1 = 1;
mainHandler.sendMessage(message);
}
}.start();
示例中通過sendMessage()方法發(fā)送消息欢唾,并且為什么最后又可以在Handler的handleMessage()方法中重新得到這條Message?接著就通過發(fā)送消息這個(gè)源碼流程來分析其原因粉捻。Handler中提供了很多個(gè)發(fā)送消息的方法礁遣,除了sendMessageAtFrontOfQueue()方法之外,其它的發(fā)送消息方法最終都會(huì)輾轉(zhuǎn)調(diào)用到sendMessageAtTime()方法中肩刃,分別看下這兩個(gè)方法的源碼祟霍,sendMessageAtTime源碼如下
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
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, uptimeMillis);
}
sendMessageAtFrontOfQueue方法源碼
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);
}
對比上面兩個(gè)方法杏头,表面上說Handler的sendMessageAtFrontOfQueue方法和其他發(fā)送方法不同,其實(shí)實(shí)質(zhì)是相同的沸呐,僅僅是sendMessageAtFrontOfQueue方法是sendMessageAtTime方法的一個(gè)特例而已醇王,即sendMessageAtTime最后一個(gè)參數(shù)uptimeMillis傳遞0。
因此崭添,只要分析sendMessageAtTime這個(gè)方法寓娩,sendMessageAtTime(Message msg, long uptimeMillis)方法有兩個(gè)參數(shù):
msg:是我們發(fā)送的Message對象,
uptimeMillis:表示發(fā)送消息的時(shí)間呼渣,uptimeMillis的值等于從系統(tǒng)開機(jī)到當(dāng)前時(shí)間的毫秒數(shù)再加上延遲時(shí)間棘伴。
最后,該方法返回一個(gè)enqueueMessage方法的返回值徙邻,那么enqueueMessage()方法毫無疑問就是入隊(duì)的方法了排嫌,我們來看下這個(gè)方法的源碼:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
方法中msg.target就是Handler對象本身畸裳;queue就是上一步傳過來的mQueue缰犁,而mQueue是在Handler實(shí)例化時(shí)構(gòu)造函數(shù)中實(shí)例化的MessageQueue實(shí)例。在Handler的構(gòu)造函數(shù)中可以看見mQueue = mLooper.mQueue;接著就調(diào)用MessageQueue中的enqueueMessage方法:
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
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) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
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;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
可以看到這里MessageQueue根據(jù)時(shí)間將所有的Message排序怖糊,然后使用鏈表的形式將所有的Message保存起來帅容。
介紹完Handle發(fā)送消息后,把消息插入到MessageQueue消息隊(duì)列后伍伤,那么回到之前l(fā)oop方法中不斷的從MessageQueue中通過next()取消息并徘,然后交由msg.target的dispatchMessage()方法處理。由之前分析可知msg.target指的是Handle對象扰魂,那么看下Handle中dispatchMessage()方法的源碼:
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
dispatchMessage方法中的邏輯比較簡單麦乞,具體就是如果msg.callback不為空,則調(diào)用handleCallback()方法處理劝评,如果mCallback不為空姐直,則調(diào)用mCallback的handleMessage()方法,否則直接調(diào)用Handler的handleMessage()方法蒋畜,并將消息對象作為參數(shù)傳遞過去声畏。這樣整個(gè)異步消息流程就串起來了。
四 總結(jié)
1.主線程中可以直接定義Handler姻成,但如果想要在子線程中定義Handler插龄,剛在創(chuàng)建Handler前需要調(diào)用Looper.prepare();,子線程中的標(biāo)準(zhǔn)的寫法形式為:
//子線程中創(chuàng)建handler
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
threadHandler = new Handler();
Looper.loop();
}
}).start();
2.一個(gè)線程中只存在一個(gè)Looper對象科展,只存在一個(gè)MessageQueue對象均牢,但可以可以有多個(gè)Handler對象,即Handler對象內(nèi)部關(guān)聯(lián)了本線程中唯一的Looper對象才睹,Looper對象內(nèi)部關(guān)聯(lián)著唯一的一個(gè)MessageQueue對象徘跪。
3.MessageQueue消息隊(duì)列是按照時(shí)間排序以鏈表的形式進(jìn)行消息存儲的见秤。