背景
最近在使用Handler输钩,想搞清楚他的原理营罢,在網(wǎng)上看了好幾篇文章都看的云里霧里的赏陵,直到看到了任玉剛老師的文章我才有了“啊,原來(lái)是這樣饲漾!”的感覺(jué)蝙搔。他的博客一再提分享精神,對(duì)我感觸很大考传。所以決定把自己對(duì)Handler的想法給大家分享一下吃型, 哪里有不對(duì)的地方聯(lián)系我, 我們一起探討一起進(jìn)步僚楞。
前言
我們大家都知道Android為了滿足線程間的通信為我們提供了Looper和Handler勤晚。相信大家也都知道Handler怎么使用,可是Handler為什么要這么用呢泉褐?什么原理呢兴枯?今天不討論他怎么用,我們來(lái)分析一下他的工作流程。如果堅(jiān)持讀到最后夕膀,相信你一定會(huì)有所收獲的(ps:哪位小伙伴不了解用法可以留言,空閑下來(lái)我會(huì)寫(xiě)一篇用法供你了解)
正文
消息機(jī)制的工作流程:
我們先來(lái)看一下他的流程圖
????最開(kāi)始先由執(zhí)行任務(wù)的線程通過(guò)Handler發(fā)送消息即去向MessageQueu(消息隊(duì)列)去插入一條消息具壮,然后Looper從MessageQueue中不斷地循環(huán)來(lái)取出消息攘已,經(jīng)由Looper處理最終將他交給了Hanlder,這樣最終就由Handler所在的線程來(lái)處理這條消息了看幼。想必大家還是不太清楚搏熄,讓我們接下來(lái)詳細(xì)的分析一下每個(gè)步驟鞋囊。
MessageQueue(消息隊(duì)列)
我們先來(lái)看一下他的源碼
public final class MessageQueue {
.....
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 {
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;
}
.....
Message next() {
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;
}
if (mQuitting) {
dispose();
return null;
}
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);
}
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);
}
}
}
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}
}
代碼比較長(zhǎng)夯缺,大家不用深究棵里,看代碼我們不難發(fā)現(xiàn)實(shí)際上他就是一個(gè)鏈表典蝌。通過(guò)enqueueMessage()方法來(lái)插入消息昔脯,通過(guò)next()來(lái)返回并移除消息,這就是MessageQueue的工作原理,讓我們先記住這兩個(gè)方法的名字。
Looper
我們還是先來(lái)看一下代碼在做解釋
public final class Looper {
......
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));
}
}
先來(lái)看一下他的prepare()方法脯倒,首先他先做了一個(gè)判斷郁岩,如果已經(jīng)存在了Looper他就會(huì)拋出
throw new RuntimeException("Only one Looper may be created per thread");
這也就是為什么一個(gè)線程只能存在一個(gè)Looper的原因。讓我們繼續(xù)向下看
public final class Looper {
......
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;
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // 注意這里H绲稹1尽!
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg); //注意這里!S环小歇终!
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
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();
}
}
}
從代碼我們可以看出內(nèi)部就是一個(gè)無(wú)限循環(huán),不斷地調(diào)用MessageQueue的next()方法來(lái)取出消息逼龟,沒(méi)錯(cuò)就是之前讓你記住MessageQueue中的兩個(gè)方法之一评凝。最后執(zhí)行這行代碼
msg.target.dispatchMessage(msg); //注意這里!O俾伞奕短!
這里的msg.target就是我們所說(shuō)的Handler(),沒(méi)錯(cuò),就是在這里將我們的消息最終交給了Handler匀钧。也許你會(huì)說(shuō):你說(shuō)是就是啊我們?cè)趺粗滥阌袥](méi)有騙我翎碑。
public final class Message implements Parcelable {
........
Handler target;
.......
}
這回你信了吧。這里L(fēng)ooper你應(yīng)該明白了之斯,經(jīng)過(guò)Looper的處理最終將消息交給了我們的Handler日杈,讓我們繼續(xù)看Handler。
Handler
我們先來(lái)看他的sendMessage().
public final boolean sendMessage(Message msg){
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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);//注意這里S铀ⅰ4镆!
}
經(jīng)過(guò)sendMessage的層層調(diào)用项乒,最后我們發(fā)現(xiàn)他調(diào)用了enqueueMessage(),也就是最開(kāi)始我們記住的兩個(gè)方法之一梁沧,就是向MessageQueue中插入消息檀何。這也就是我們的發(fā)送階段。我們還記得Looper最后調(diào)用了Handler的dispatchMessage()廷支,他內(nèi)部是什么機(jī)制呢频鉴,讓我們來(lái)看一下。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);//注意這里A蹬摹6饪住!
}
}
到了這里我相信大家一定不會(huì)陌生了吧施敢,看到了我們最熟悉的handleMessage()了周荐。這里就到了Handler對(duì)消息的處理階段了, 現(xiàn)在我們就可以在Handler所在的線程做自己想做的處理了僵娃。
尾語(yǔ)
到這里消息機(jī)制的流程我們已經(jīng)梳理完了概作,各部分的原理相信你也有了一定的了解,相信你現(xiàn)在回過(guò)頭去看前面的流程圖已經(jīng)有了不一樣的感覺(jué)了默怨。本人能力有限讯榕,只想分享一下自己的見(jiàn)解,希望我們一起進(jìn)步,有什么疏漏一定要聯(lián)系我哦S奁ā<弥瘛!很樂(lè)意與你交流探討v薄K妥恰!
注T匝唷:贝!
總結(jié)不易碍岔,請(qǐng)尊重勞動(dòng)成果浴讯,轉(zhuǎn)載請(qǐng)標(biāo)明出處,謝謝0病S芘Α!