在android項目的開發中我們經常會有需求在其他線程內更新UI界面,但是系統並不允許我們這麼幹。android的UI系統被設計成單線程訪問模式,深究其原因,無非也是擔心在多線程訪問的情況下可能會導致界面更新的混亂,最終形成了這種界面只能在UI線程中進行更新的結局。但是android自身給我們提供了一些很方便的方法可以讓我們在其他線程中容易的更新UI界面,其中最典型的有asynctask,handler等。handler應該是每一個安卓開發者最早接觸的更新UI界面的方法,操作非常的簡單,但是內部的實現卻有大玄機,我們今天就從源碼的角度來分析一下Handler機制。
提到handler就不得不提它的兩個兄弟,messageQueue和Looper。也許以前從來沒聽說過他們,不過沒關係,我們一步一步向下看。
我們先來直觀的看一下整個流程的圖示,方便進行理解:
其他線程中持有主線程Handler的引用,然後將message信息發送到主線程中的messageQueue消息隊列中,有Looper負責取出,然後返回給主線程中的Handler進行處理,一切看起來還是很清晰的,我們從最常用的Handler開始入手
在使用Hanlder來更新UI界面的時候,我們在子線程中最常用的無非就是Hanlder的send方法和post方法了,來看一下最常用的幾個函數的源碼:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
在sendEmptyMessage方法中調用了sendEmptyMessageDelayed方法,我們繼續看:
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
調用了同一個sendMessageDelayed方法,我們進入看一下:
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
接着進入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);
}
終於露出真容了,在方法中判斷了mQueue是不是爲空,如果爲空拋出異常,如果不爲空調用enqueueMessage方法,見名知意,方法應該完成了把傳入的Message入隊,我們進入方法看一下:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
看起來上面的分析沒錯,的確調用了mQueue的方法將message入隊,這裏注意一點細節,入隊的msg的target屬性被賦值爲this,也就是當前的Handler,這點在後文中會提到。現在整個操作已經到了底端,再向下進入就要進到MessageQueue的方法中去了,但是我們還沒處理一個問題,Handler中的mQueue對象到底是怎麼來的?
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;
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
在Handler源碼中的構造方法最終都能歸結爲這兩個,而兩個構造方法都顯示了mQueue都是Looper類對象的屬性。在第二個構造方法中looper對象是直接傳入的,我們暫且不去深究,而第一個方法中mLooper對象是由Looper類的靜態mLooper方法獲得的,我們看一下這個方法:
public static Looper myLooper() {
return sThreadLocal.get();
}
只有一行代碼,我們來看一下sThreadLocal是什麼:
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
上面的註釋說的很清楚,如果沒有調用prepare方法,這個sThreadLocal會返回null,進入prepare看一下:
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));
}
分析到這裏我們應該有一些小結論了,在new出Handler的對象之前必須調用Looper的prepare方法,不然就會拋出異常,而且這個方法在同一個線程中只能調用一次,不然還是會拋異常。在Handler所在線程中獲取的Looper是和Handler在同一線程的,這點在ThreadLocal分析的文章中也有提過。
繼續下行,在prepare方法中我們創建了Looper類的對象,現在看一下構造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mRun = true;
mThread = Thread.currentThread();
}
在這裏將mQueue創建出來了,至此,我們提出的Handler中如何創建出mQueue對象的問題就算是解決了。在常規的步驟下,如果在非UI線程中讓Hanlder機制工作的話,我們需要有以下幾個步驟(UI線程在後面會提到):
Looper.prepare();
Handler handler = new Handler();
Looper.loop();
前兩部我們都已經分析了,現在來看一下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;
}
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
msg.recycle();
}
}
以上就是loop方法的代碼(在這裏我將一些打印日誌的語句刪掉了),可以看到在方法中是一個無限循環,而退出的條件是當前Looper對象所持有的mQueue中的next方法返回null。爲了能看懂這段代碼的含義,我們必須去看一下MessageQueue的實現。在上文中我們已經分析了,Handler中的send方法調用的本質就是向mQueue中入隊一條消息,這裏我們看一下MessageQueue的enqueue方法:
final boolean enqueueMessage(Message msg, long when) {
if (msg.isInUse()) {
throw new AndroidRuntimeException(msg + " This message is already in use.");
}
if (msg.target == null) {
throw new AndroidRuntimeException("Message must have a target.");
}
boolean needWake;
synchronized (this) {
if (mQuiting) {
RuntimeException e = new RuntimeException(
msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
return false;
}
msg.when = when;
Message p = mMessages;
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;
}
}
if (needWake) {
nativeWake(mPtr);
}
return true;
}
代碼感覺上有點長,我們只分析關鍵部分。在同步塊中間的if-else語句中看到了熟悉的代碼,是一個鏈表的實現,將新來的消息插入到了鏈表的最後。這樣我們將入隊的操作也分析完了,在上面Looper的loop方法中調用了mQueue.next(),來看一下next方法的實現:
final Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(mPtr, nextPollTimeoutMillis);
synchronized (this) {
if (mQuiting) {
return null;
}
// 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 (false) Log.v("MessageQueue", "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// 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("MessageQueue", "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;
}
}
還是來關注主要的邏輯,這段代碼中還是嵌套這for(,,)這樣的無限循環語句,在其中發現返回值的地方只有一處,其中將一個Message對象返回了。那麼,當隊列中沒有對象時,由於無線循環的原因調用next方法就會一直處於阻塞狀態,只要一向隊列中添加了一條Message,next方法就會將它返回。現在回頭來看上文中Looper類的loop方法,如果沒有消息到來,Message msg = queue.next();就會一直阻塞,這也是後面註釋給出的解釋。
我們重新來看Looper中的loop方法,由於其中的無線循環,它在不停的探測next方法是否返回了Message,如果返回了,馬上進行下一步處理,也就是 msg.target.dispatchMessage(msg);然後將Message對象重新放入池中。當然無限循環總是要有出口的,在loop方法中出口就是next方法返回null,回過頭看一下next方法,能返回null的地方只有一個,就是當mQuiting屬性爲true的時候,再來看一下這個屬性是怎麼賦值的:
final void quit() {
if (!mQuitAllowed) {
throw new RuntimeException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuiting) {
return;
}
mQuiting = true;
}
nativeWake(mPtr);
}
在MessageQueue中quit方法將其設置爲true,那麼這個方法又是被誰調用的呢,我們找一下源碼,最終在Looper類中找到這樣一個方法:
public void quit() {
mQueue.quit();
}
現在我們也能得出一點小結論了,Looper本身的quit方法調用時,它就會停止從MessageQueue中索取對象。換句話說,在Looper不用的時候,要調用quit方法及時將無限循環停止。
剛纔說到loop方法中一旦拿到了Message對象將會執行msg.target.dispatchMessage(msg);,記得在源碼分析的開始提到過這個target,它就是最開始的那個Handler,所以看一下Handler中的dispatchMessage方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
方法開始判斷msg的callback是否爲空,不爲空就執行handlerCallback方法,由於msg就是通過handler傳出去的,所以callback也一定在handler中找得到:
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean postAtTime(Runnable r, long uptimeMillis)
{
return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}
public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
{
return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
}
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
public final boolean postAtFrontOfQueue(Runnable r)
{
return sendMessageAtFrontOfQueue(getPostMessage(r));
}
可以看到,每個post方法都傳遞了一個Runnable對象進來,並且都調用了getPostMessage方法,跟進看一下:
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
private static Message getPostMessage(Runnable r, Object token) {
Message m = Message.obtain();
m.obj = token;
m.callback = r;
return m;
}
callback正是我們傳入的Runnable對象。然後看一下handleCallback方法:
private static void handleCallback(Message message) {
message.callback.run();
}
僅僅將Runnable對象的run方法跑了一遍,但是這裏要清楚,run方法是在handler線程中跑的,如果我們在UI線程中定義Handler然後在其他線程post了Runnable對象,還是會造成ANR。
繼續看Handler中的dispatchMessage方法,如果mCallBack不爲空,則執行它的handlerMessage方法。看一下mCallBack的來歷:
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;
}
又一次回到了構造函數中,如果我們傳入的一個Callback對象,那麼它的handlerMessage方法將被執行。如果我們沒傳Callback,那麼Handler中的handlerMessage方法將被執行,這和我們經常寫的代碼邏輯是一樣的,new出Handler對象,重寫handleMessage方法。那麼Callback也給我們提供了一種新的思路,可以不重寫hanlder中的handlerMessage方法,而是提供Callback接口,然後實現其中的方法:
public interface Callback {
public boolean handleMessage(Message msg);
}
到這裏分析就結束了,相信上面的示例圖也能容易的看懂。在上面的分析中提到創建Handler對象之前一定要調用Looper的prepare方法,但是我們在主線程中創建卻從來沒調用這個方法,也沒有出現異常,原因是安卓的主線程自動幫我們執行了Looper的prepareMainLooper方法,如果有興趣可以自己看一下源碼,這裏就不再贅述了。