一提到Android的消息機(jī)制汰聋,相信各位看官一定會(huì)馬上聯(lián)想到Handler门粪,Handler作為更新UI的神器之一,我們?cè)谌粘i_(kāi)發(fā)中也就自然而然地會(huì)頻繁涉及這方面的內(nèi)容烹困,今天在《輕松而深入理解Android的消息機(jī)制》系列第一篇中玄妈,我們就來(lái)梳理一下Handler的運(yùn)行機(jī)制。
Handler的實(shí)際作用
我們大多數(shù)使用Handler都是為了去更新UI髓梅,但實(shí)際上Handler的功能不僅僅如此拟蜻,更新UI也只是Handler的一個(gè)特殊使用場(chǎng)景。Handler的作用主要有兩個(gè):
a.控制某個(gè)任務(wù)的開(kāi)始執(zhí)行時(shí)間;
b.將某個(gè)任務(wù)切換到指定線程中執(zhí)行枯饿。
簡(jiǎn)述Handler的運(yùn)行機(jī)制
Handler運(yùn)行機(jī)制實(shí)際上是Handler酝锅、Looper和MessageQueue三者共同協(xié)作的工作過(guò)程。
Looper:消息循環(huán)奢方,無(wú)限循環(huán)查詢是否有新消息處理搔扁,若沒(méi)有則等待。
MessageQueue:消息隊(duì)列蟋字,它的內(nèi)部存儲(chǔ)了一組消息稿蹲,以隊(duì)列的形式對(duì)外提供插入和刪除工作,其只是一個(gè)消息的存儲(chǔ)單元愉老,并不能去處理消息场绿。
Handler創(chuàng)建時(shí)會(huì)采用當(dāng)前線程的Looper,并獲取到Looper中的MessageQueue來(lái)構(gòu)建內(nèi)部的消息循環(huán)系統(tǒng)嫉入,若當(dāng)前線程沒(méi)有Looper焰盗,則會(huì)拋出RuntimeException。Handler創(chuàng)建完畢后咒林,當(dāng)Handler的post方法或者send方法被調(diào)用時(shí)熬拒,Handler會(huì)將消息插入到消息隊(duì)列中,而后當(dāng)Looper發(fā)現(xiàn)有新消息到來(lái)時(shí)垫竞,就會(huì)處理這個(gè)消息澎粟,最終消息的處理過(guò)程會(huì)在消息中的Runnable或者Handler的handleMessage方法中執(zhí)行蛀序。
為了便于理解,我們可以將上述過(guò)程類比為工廠的生長(zhǎng)線活烙,Handler是工人徐裸,負(fù)責(zé)產(chǎn)品的投放和包裝,Looper是發(fā)動(dòng)機(jī)啸盏,一直處于開(kāi)啟狀態(tài)重贺,MessageQueue是傳送帶,產(chǎn)品當(dāng)然就是Message了回懦。
此處上圖:
Handler的工作原理
Handler的工作主要包含消息的發(fā)送和接受過(guò)程气笙。
Handler的創(chuàng)建
Handler有兩個(gè)構(gòu)造方法需要留意一下:
a.當(dāng)我們創(chuàng)建Handler時(shí)不傳入Looper時(shí)會(huì)調(diào)用此構(gòu)造方法,從代碼中我們可以很輕易地找到在沒(méi)有Looper的子線程中創(chuàng)建Handler會(huì)引發(fā)程序異常的原因怯晕。
public Handler(Callback callback, boolean async) {
...
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;
}
b.創(chuàng)建Handler時(shí)傳入Looper時(shí)會(huì)調(diào)用此構(gòu)造方法
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
發(fā)送消息
消息的發(fā)送可以通過(guò)post的一系列方法以及send的一系列方法來(lái)實(shí)現(xiàn)潜圃,post的一系列方法最終也是通過(guò)send的一系列方法來(lái)實(shí)現(xiàn)的,這里需要注意的是send方法傳入的是Message對(duì)象舟茶,而post方法傳入的是Runnable對(duì)象谭期,而這個(gè)Runnable對(duì)象又會(huì)被存儲(chǔ)在msg.callback中。
public final boolean post(Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
從上面的流程圖中稚晚,我們可以清晰地看到無(wú)論是post方法還是send方法最終都會(huì)調(diào)用enqueueMessage方法崇堵,而從代碼也可以看出,Handler發(fā)送消息的過(guò)程僅僅是向隊(duì)列中插入一條消息的過(guò)程客燕。
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
// 這里需要特別注意鸳劳,將當(dāng)前Handler保存于Message.target中
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
接收消息
Handler向隊(duì)列中插入一條消息后,最后會(huì)經(jīng)過(guò)Looper處理交由Handler處理也搓,此時(shí)Handler的dispatchMessage方法會(huì)被調(diào)用赏廓。
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 != null傍妒,msg.callback似曾相識(shí)啊幔摸,沒(méi)錯(cuò),前面提到了調(diào)用post方法時(shí)傳入的Runable對(duì)象會(huì)存儲(chǔ)在Message.callback中颤练,handleCallback的邏輯如下:
private static void handleCallback(Message message) {
message.callback.run();
}
在Handler類中既忆,有一個(gè)接口類Callback,實(shí)現(xiàn)這個(gè)接口需要實(shí)現(xiàn)handleMessage(Message msg)方法嗦玖,這個(gè)類到底有什么用呢患雇?我們都知道Handler類中有一個(gè)空方法handleMessage(Message msg) ,所有Handler的子類必須實(shí)現(xiàn)這個(gè)方法宇挫,而Callback的存在也就使得當(dāng)我們需要?jiǎng)?chuàng)建一個(gè)Handler的實(shí)例時(shí)苛吱,我們就不必再派生Handler的子類了。
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
final Callback mCallback;
public interface Callback {
/**
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
public boolean handleMessage(Message msg);
}
梳理完了Handler的工作原理器瘪,接下里再來(lái)分析Looper的工作原理翠储。
Looper的工作原理
Looper在Android的消息機(jī)制中扮演著消息循環(huán)的角色绘雁,它會(huì)不停地從MessageQueue中查看是否有新消息,如果有新消息就會(huì)立刻處理援所,否則就一直阻塞在那里庐舟。
Looper的創(chuàng)建
在Looper的構(gòu)造方法中,Looper創(chuàng)建一個(gè)MessageQueue任斋,并且保存了當(dāng)前線程继阻。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
我們知道Handler的工作需要Looper,而線程默認(rèn)是沒(méi)有Looper的废酷,所以在沒(méi)有Looper的線程中我們需要通過(guò)Looper.prepare()方法為當(dāng)前線程創(chuàng)建一個(gè)Looper,在Looper被創(chuàng)建的同時(shí)會(huì)將自己保存到自己所在線程的threadLocals變量中抹缕。
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
public static void prepare() {
prepare(true);
}
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));
}
ThreadLocal<T>
ThreadLocal是一個(gè)線程內(nèi)部的數(shù)據(jù)存儲(chǔ)類澈蟆,其最大的作用在于可以在多個(gè)線程中互不干擾地存儲(chǔ)和修改數(shù)據(jù),這也是解決多線程的并發(fā)問(wèn)題的思路之一卓研。當(dāng)不同線程訪問(wèn)同一個(gè)ThreadLocal的get方法趴俘,ThreadLocal內(nèi)部會(huì)從各自的線程中取出一個(gè)數(shù)組,然后再?gòu)臄?shù)組中根據(jù)當(dāng)前ThreadLocal的索引去查找出對(duì)應(yīng)的value值奏赘。
ThreadLocal實(shí)際上是一個(gè)泛型類寥闪,其定義為public class ThreadLocal<T>,在Thread類內(nèi)部有一個(gè)成員專門用于存儲(chǔ)線程的ThreadLocal的數(shù)據(jù):ThreadLocal.ThreadLocalMap threadLocals磨淌。
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
loop()
這個(gè)方法是Looper類中最重要的一個(gè)方法疲憋,只有在調(diào)用loop方法后,消息循環(huán)系統(tǒng)才會(huì)真正地啟動(dòng)梁只。
loop方法首先會(huì)獲取當(dāng)前線程所保存的Looper對(duì)象和MessageQueue對(duì)象缚柳,然后調(diào)用MessageQueue的next方法來(lái)獲取新消息,而next是一個(gè)阻塞操作搪锣,當(dāng)沒(méi)有消息時(shí)秋忙,next方法會(huì)一直阻塞在這里。當(dāng)MessageQueue的next方法返回null時(shí)构舟,loop的死循環(huán)會(huì)跳出灰追。當(dāng)MessageQueue的next返回新消息時(shí),Looper就會(huì)處理這條消息狗超,即msg.target.dispatchMessage(msg)弹澎,在Handler的enqueueMessage方法可以看到,msg.target實(shí)際上就是發(fā)送這條消息的Handler對(duì)象抡谐,因此Handler發(fā)送的消息最終就還是交給了其dispatchMessage方法來(lái)處理裁奇,此時(shí)Handler的dispatchMessage方法是在創(chuàng)建Handler時(shí)所使用的Looper中執(zhí)行的,也就成功將代碼邏輯切換到指定的線程中去執(zhí)行了麦撵。
/**
* 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();
}
/**
* 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;
}
...
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
...
msg.recycleUnchecked();
}
}
quit()和quitSafely()
在子線程中刽肠,若手動(dòng)為其創(chuàng)建了Looper溃肪,則在所有的事情處理完成后應(yīng)調(diào)用quit方法來(lái)終止消息循環(huán),否則此線程會(huì)一直處于等待狀態(tài)音五。
quit()會(huì)直接退出Looper惫撰,quitSafely()只是設(shè)定一個(gè)退出標(biāo)記,待消息隊(duì)列已有消息處理完畢后再安全退出躺涝。
public void quit() {
mQueue.quit(false);
}
public void quitSafely() {
mQueue.quit(true);
}
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);
}
}
Looper的工作原理就分析到這里了厨钻,下面我們?cè)賮?lái)看看MessageQueue的工作原理
MessageQueue的工作原理
MessageQueue的內(nèi)部存儲(chǔ)結(jié)構(gòu)并不是真正的隊(duì)列,而是采用單鏈表的數(shù)據(jù)結(jié)構(gòu)來(lái)存儲(chǔ)消息隊(duì)列坚嗜,單鏈表在插入和刪除數(shù)據(jù)上是比較有優(yōu)勢(shì)的夯膀。
MessageQueue主要包含兩個(gè)操作:插入和讀取。讀取操作本身會(huì)伴隨著刪除操作苍蔬,插入和讀取對(duì)應(yīng)的方法分別為enqueueMessage和next诱建,其中enqueueMessage的作用是往消息隊(duì)列中插入一條消息,而next的作用是從消息隊(duì)列中取出一條消息并將其從消息隊(duì)列移除碟绑。
插入數(shù)據(jù):enqueueMessage()
上邊提到過(guò)俺猿,Handler的enqueueMessage方法會(huì)向MessageQueue插入數(shù)據(jù),此時(shí)MessageQueue的enqueueMessage方法會(huì)被調(diào)用格仲,從代碼可以看到押袍,enqueueMessage的要操作實(shí)質(zhì)上就是單鏈表的插入操作。
這里提一下mQuitting這個(gè)布爾變量凯肋,當(dāng)消息循環(huán)退出時(shí)(MessageQueue的quit()方法被調(diào)用時(shí))谊惭,mQuitting的值為true,此后通過(guò)Handler發(fā)送的消息都會(huì)返回false否过,也就是我們所說(shuō)的發(fā)送失敗午笛。
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;
}
讀取數(shù)據(jù):next()
next是一個(gè)無(wú)限循環(huán)的方法,如果消息隊(duì)列中沒(méi)有消息苗桂,next會(huì)一直阻塞在這里药磺;當(dāng)有新消息時(shí),next會(huì)返回這條消息并將其從單鏈表中移除煤伟。
當(dāng)mQuitting值為true時(shí)癌佩,next方法會(huì)返回null,即Looper.loop方法跳出了死循環(huán)便锨。
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;
}
}
到這里围辙,Handler的運(yùn)行機(jī)制的基本流程也就介紹完畢了,最后再來(lái)簡(jiǎn)單說(shuō)一下主線程的消息循環(huán)放案。
主線程的消息循環(huán)
上面提到過(guò)姚建,Handler的使用必須需要在當(dāng)前線程中創(chuàng)建Looper,然而在實(shí)際開(kāi)發(fā)中吱殉,我們?cè)谥骶€程使用Handler時(shí)卻沒(méi)有創(chuàng)建Looper掸冤,這是因?yàn)橹骶€程在被創(chuàng)建時(shí)就會(huì)初始化了Looper厘托,所以主線程中是默認(rèn)可以使用Handler的。
大家都知道Android的主線程就是ActivityThread稿湿,主線程(UI線程)的入口方法為main铅匹,在main方法中系統(tǒng)會(huì)通過(guò)Looper.prepareMainLooper()來(lái)創(chuàng)建主線程的Looper以及MessageQueue,并通過(guò)Looper.loop()來(lái)開(kāi)啟主線程的消息循環(huán)饺藤。此后Looper會(huì)一直從消息隊(duì)列中取消息包斑,然后處理消息。用戶或者系統(tǒng)通過(guò)Handler不斷地往消息隊(duì)列中插入消息涕俗,這些消息不斷地被取出罗丰、處理、回收再姑,使得應(yīng)用迅速地運(yùn)轉(zhuǎn)起來(lái)丸卷。
public static void main(String[] args) {
...
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");
}
Looper#prepareMainLooper
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
這就是本篇文章的全部?jī)?nèi)容了,在下一篇中我們還會(huì)繼續(xù)梳理一下和Android消息機(jī)制相關(guān)的其他知識(shí)询刹。由于本人的能力和水平有限,難免會(huì)出現(xiàn)錯(cuò)誤萎坷,如有發(fā)現(xiàn)還望大家指正凹联。
參考書籍:《Android開(kāi)發(fā)藝術(shù)探索》