背景
最近在使用Handler,想搞清楚他的原理,在網上看了好幾篇文章都看的云里霧里的,直到看到了任玉剛老師的文章我才有了“啊,原來是這樣!”的感覺。他的博客一再提分享精神,對我感觸很大。所以決定把自己對Handler的想法給大家分享一下, 哪里有不對的地方聯系我, 我們一起探討一起進步。
前言
我們大家都知道Android為了滿足線程間的通信為我們提供了Looper和Handler。相信大家也都知道Handler怎么使用,可是Handler為什么要這么用呢?什么原理呢?今天不討論他怎么用,我們來分析一下他的工作流程。如果堅持讀到最后,相信你一定會有所收獲的(ps:哪位小伙伴不了解用法可以留言,空閑下來我會寫一篇用法供你了解)
正文
消息機制的工作流程:
我們先來看一下他的流程圖
????最開始先由執行任務的線程通過Handler發送消息即去向MessageQueu(消息隊列)去插入一條消息,然后Looper從MessageQueue中不斷地循環來取出消息,經由Looper處理最終將他交給了Hanlder,這樣最終就由Handler所在的線程來處理這條消息了。想必大家還是不太清楚,讓我們接下來詳細的分析一下每個步驟。
MessageQueue(消息隊列)
我們先來看一下他的源碼
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;
}
}
}
代碼比較長,大家不用深究,看代碼我們不難發現實際上他就是一個鏈表。通過enqueueMessage()方法來插入消息,通過next()來返回并移除消息,這就是MessageQueue的工作原理,讓我們先記住這兩個方法的名字。
Looper
我們還是先來看一下代碼在做解釋
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));
}
}
先來看一下他的prepare()方法,首先他先做了一個判斷,如果已經存在了Looper他就會拋出
throw new RuntimeException("Only one Looper may be created per thread");
這也就是為什么一個線程只能存在一個Looper的原因。讓我們繼續向下看
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(); // 注意這里!??!
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); //注意這里?。。?
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();
}
}
}
從代碼我們可以看出內部就是一個無限循環,不斷地調用MessageQueue的next()方法來取出消息,沒錯就是之前讓你記住MessageQueue中的兩個方法之一。最后執行這行代碼
msg.target.dispatchMessage(msg); //注意這里?。。?
這里的msg.target就是我們所說的Handler(),沒錯,就是在這里將我們的消息最終交給了Handler。也許你會說:你說是就是啊我們怎么知道你有沒有騙我。
public final class Message implements Parcelable {
........
Handler target;
.......
}
這回你信了吧。這里Looper你應該明白了,經過Looper的處理最終將消息交給了我們的Handler,讓我們繼續看Handler。
Handler
我們先來看他的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);//注意這里?。。? }
經過sendMessage的層層調用,最后我們發現他調用了enqueueMessage(),也就是最開始我們記住的兩個方法之一,就是向MessageQueue中插入消息。這也就是我們的發送階段。我們還記得Looper最后調用了Handler的dispatchMessage(),他內部是什么機制呢,讓我們來看一下。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);//注意這里?。。? }
}
到了這里我相信大家一定不會陌生了吧,看到了我們最熟悉的handleMessage()了。這里就到了Handler對消息的處理階段了, 現在我們就可以在Handler所在的線程做自己想做的處理了。
尾語
到這里消息機制的流程我們已經梳理完了,各部分的原理相信你也有了一定的了解,相信你現在回過頭去看前面的流程圖已經有了不一樣的感覺了。本人能力有限,只想分享一下自己的見解,希望我們一起進步,有什么疏漏一定要聯系我哦?。?!很樂意與你交流探討!??!
注?。?!
總結不易,請尊重勞動成果,轉載請標明出處,謝謝!!!