我們知道,在android開(kāi)發(fā)中,耗時(shí)操作是不能再主線程中執(zhí)行的,否則會(huì)導(dǎo)致ANR。但是我們又不能在子線程中去更新UI,因?yàn)楣芾韛iew繪制的ViewRootImpl會(huì)檢查線程
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
在這種場(chǎng)景下,我們一般會(huì)用到android中的消息機(jī)制,即Handler。Handler的作用和使用方法這里就不細(xì)說(shuō)了。這里主要觀察Handler的功能是如何實(shí)現(xiàn)的。
看一下Handler的構(gòu)造函數(shù),Handler的構(gòu)造函數(shù)很多,但最終都會(huì)回調(diào)到這里
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;
}
從上面的構(gòu)造函數(shù)可以看到,如果Looper為null的話,會(huì)拋出異常。即在使用Handler前必須構(gòu)造Looper。那為什么我們平時(shí)使用的時(shí)候沒(méi)有構(gòu)造這個(gè)Looper呢。這是因?yàn)槲覀兊腢I線程也就是ActivityThread,在主線程的入口main方法中會(huì)通過(guò)Looper.prepareMainLooper()方法來(lái)創(chuàng)建主線程的Looper。具體的下面會(huì)講,這里我們知道,Handler必須配合Looper使用。而Looper內(nèi)有一個(gè)屬性是MessageQueue,所以我們先來(lái)看一下MessageQueue
MessageQueue
MessageQueue即android中的消息隊(duì)列,是通過(guò)單鏈表實(shí)現(xiàn)的,因?yàn)閱捂湵碓跀?shù)據(jù)插入和刪除上比較有優(yōu)勢(shì)。MessageQueue主要包含三個(gè)操作,enqueueMessage(),next()和quit()。分別是插入一個(gè)消息,取出并刪除一個(gè)消息,清空消息池中消息。下面看一下他們的源碼
enqueueMessage()
boolean enqueueMessage(Message msg, long when) {
//msg.target指的是Handler對(duì)象,后面會(huì)講到
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;
}
可以看到,enqueueMessage的確是向單鏈表中添加message
next()
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;
//無(wú)限循環(huán)
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;
}
}
next()方法內(nèi)部是一個(gè)無(wú)限循環(huán)。每當(dāng)消息隊(duì)列中有Message時(shí),就將這個(gè)Message返回并在鏈表中刪除
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);
}
}
參數(shù)safe為false時(shí),執(zhí)行了removeAllMessagesLocked(),該方法的作用是把MessageQueue消息池中所有的消息全部清空,無(wú)論是延遲消息(延遲消息是指通過(guò)sendMessageDelayed或通過(guò)postDelayed等方法發(fā)送的需要延遲執(zhí)行的消息)還是非延遲消息。
當(dāng)參數(shù)safe為true時(shí),執(zhí)行了removeAllFutureMessagesLocked方法,通過(guò)名字就可以看出,該方法只會(huì)清空MessageQueue消息池中所有的延遲消息,并將消息池中所有的非延遲消息派發(fā)出去讓Handler去處理,removeAllFutureMessagesLocked()相比于removeAllMessagesLocked()方法安全之處在于清空消息之前會(huì)派發(fā)所有的非延遲消息。
Looper
Looper.prepare()
Looper,顧名思義,循環(huán)
看一下Looper的構(gòu)造函數(shù)
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
這是一個(gè)私有的構(gòu)造函數(shù),不能直接調(diào)用
真正構(gòu)造Looper的是Loopre.prepare()方法和prepareMainLooper()方法:
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
//多次構(gòu)造Looper拋出異常,一個(gè)線程最多只有一個(gè)Looper
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
//如果在主線程中手動(dòng)構(gòu)造Looper則報(bào)錯(cuò),因?yàn)橹骶€程已經(jīng)有Looper了
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
結(jié)合以上方法,我們可以看到。
Looper.prepare()方法和prepareMainLooper()方法都調(diào)用了prepare();
而prepare()方法很簡(jiǎn)單,new了一個(gè)Looper并添加到ThreadLocal(功能見(jiàn)下面說(shuō)明)。
這里的quitAllowed指的是當(dāng)前Looper循環(huán)是否允許退出,這也是子線程Looper和UI線程Looper構(gòu)造時(shí)的區(qū)別。即主線程的Looper不允許退出循環(huán),而子線程的Looper可以退出循環(huán)
Android給我們提供了兩個(gè)退出Looper循環(huán)的方法:
public void quit() {
mQueue.quit(false);
}
和
public void quitSafely() {
mQueue.quit(true);
}
一目了然,只是調(diào)用了MessageQueue內(nèi)部的quit方法,上面已經(jīng)講過(guò)。需要補(bǔ)充的是,無(wú)論是調(diào)用了quit方法還是quitSafely方法只會(huì),Looper就不再接收新的消息。即在調(diào)用了Looper的quit或quitSafely方法之后,消息循環(huán)就終結(jié)了,這時(shí)候再通過(guò)Handler調(diào)用sendMessage或post等方法發(fā)送消息時(shí)均返回false,表示消息沒(méi)有成功放入消息隊(duì)列MessageQueue中,因?yàn)橄㈥?duì)列已經(jīng)退出了。
重點(diǎn):如果我們手動(dòng)創(chuàng)建了Looper處理事務(wù),當(dāng)事務(wù)處理完成之后應(yīng)該調(diào)用quit或者quitSafely方法退出循環(huán),否則這個(gè)子線程就會(huì)一直處于等待狀態(tài),如果退出循環(huán),子線程會(huì)立即終止。
所以當(dāng)我們需要構(gòu)造Looper時(shí),調(diào)用Looper.prepare()即可。調(diào)用之后,Looper的構(gòu)造函數(shù)做了兩件事:
1.new了一個(gè)MessageQueue(即消息隊(duì)列)并保存在Looper內(nèi)部。
2.將當(dāng)前線程保存在Looper內(nèi)部
說(shuō)明:這里的sThreadLocal類型是ThreadLocal。
ThreadLocal是一個(gè)線程內(nèi)部的數(shù)據(jù)儲(chǔ)存類,通過(guò)它可以在指定的線程儲(chǔ)存數(shù)據(jù),數(shù)據(jù)儲(chǔ)存后只有在指定的線程可以獲取到。
在這里,即把Looper對(duì)象儲(chǔ)存到該線程中了。需要使用的時(shí)候get出來(lái)即可。這一點(diǎn)我們可以通過(guò)Looper.myLooper()來(lái)驗(yàn)證:
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
Looper構(gòu)造完成之后,我們得讓他循環(huán)起來(lái)
Looper.loop()
看一下源碼:
public static void loop() {
//構(gòu)造完成之后,通過(guò)myLooper()取得該線程的looper
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//取出在Looper構(gòu)造函數(shù)中new的消息隊(duì)列
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();
//無(wú)限循環(huán)
for (;;) {
//我們知道,queue.next()這個(gè)方法也是無(wú)限循環(huán)的
//只有我們調(diào)用了quit方法之后queue.next()才會(huì)返回空
//也就是說(shuō),除非我們調(diào)用Looper.quit()方法,否則loop方法會(huì)一直循環(huán)下去
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 {
//獲取到消息后,調(diào)用handler的dispatchMessage方法將消息分發(fā)
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();
}
}
通過(guò)源碼可以看到,loop()方法和queue.next()一樣,也是一個(gè)無(wú)限循環(huán)的方法。并且loop()方法內(nèi)部調(diào)用了queue.next()方法。而next()是一個(gè)阻塞操作,當(dāng)消息隊(duì)列中沒(méi)有Message時(shí),queue.next()阻塞,導(dǎo)致loop()方法也一直阻塞在這里,當(dāng)消息隊(duì)列中有Message時(shí),立馬會(huì)被loop()方法獲取到。然后調(diào)用Handler的dispatchMessage()方法。而dispatchMessage()方法內(nèi)部又會(huì)根據(jù)我們傳入的參數(shù)來(lái)調(diào)用對(duì)應(yīng)的handleMessage()方法。這樣就從消息添加到消息隊(duì)列,取出消息,又回到我們熟悉的handleMessage啦。接下來(lái)我們就講講Handler
Handler
在了解了MessageQueue和Looper之后,我們回到Handler的構(gòu)造方法:
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;
}
對(duì)于上面的mLooper和mQueue我們已經(jīng)知道是咋回事了。
至于mCallback,他的類型是Callback,Callback是Handler內(nèi)部的一個(gè)interface
public interface Callback {
public boolean handleMessage(Message msg);
}
里面只有一個(gè)方法,下面還會(huì)講到,先不細(xì)說(shuō)
這里先看一下Handler是如何發(fā)送一個(gè)消息的,又是如何把消息添加到MessageQueue里的
Handler發(fā)送消息的方法很多,
但不論是什么發(fā)送方法,最后都會(huì)回調(diào)到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);
}
內(nèi)部只是判斷了一下消息隊(duì)列的合法性,接著調(diào)用了enqueueMessage()方法:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//注意:上面多次提到的msg.target即為Handler對(duì)象,在這里得到證實(shí)
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
在這里可以清楚的看到,源碼中先將該Handler對(duì)象賦值給Message的target屬性。
接著調(diào)用了queue.enqueueMessage(msg, uptimeMillis);也就是將消息插入了消息隊(duì)列當(dāng)中。
但是需要注意的是,這里的queue(消息隊(duì)列)是我們?cè)跇?gòu)造Handler時(shí),在Handler的構(gòu)造方法中新建了Looper,然后在該Looper的構(gòu)造方法中new新建了這個(gè)MessageQueue。所以,這個(gè)queue是存在于接收消息線程中的。
結(jié)合上面我們現(xiàn)在知道,當(dāng)發(fā)送一個(gè)消息的時(shí)候,首先會(huì)將Handler對(duì)象賦值給Message的target屬性,并將Message加入到這個(gè)線程對(duì)應(yīng)Looper中的MessageQueue里。然后在Looper的Loop.loop()方法中,通過(guò)MessageQueue的next()方法取得這個(gè)消息(Message)。然后調(diào)用msg.target.dispatchMessage(msg);也就是執(zhí)行了Handler的dispatchMessage()方法。這樣一來(lái),消息就從發(fā)送消息的線程發(fā)送到了接收消息的線程。
我們?cè)倏纯磀ispatchMessage()這個(gè)方法中具體做了什么:
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
//利用Handler的post()方法發(fā)送消息
if (msg.callback != null) {
handleCallback(msg);
} else {
//Handler構(gòu)造函數(shù)中的Callback
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//我們經(jīng)常復(fù)寫Handler的handleMessage()方法
handleMessage(msg);
}
}
msg.callback是啥呢?要說(shuō)清楚這個(gè),我們還是得先看看Handler的post()方法:
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
這里又把Runnable傳給了getPostMessage(r)方法,不著急,繼續(xù)看:
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
看到這里就很明白了,其實(shí)post方法在內(nèi)部new了一個(gè)Message,然后把Runable賦值給了Message的callback屬性。
所以,回到dispatchMessage方法中,如果我們利用Handler的post()方法發(fā)送消息,則msg.callback!=null,直接回調(diào)handleCallback(msg)方法:
private static void handleCallback(Message message) {
message.callback.run();
}
也就是執(zhí)行了Runable中的run()方法。沒(méi)毛病,和我們想的一樣
那么mCallback又是啥呢?還記得Handler構(gòu)造函數(shù)中的mCallback不?對(duì)的,就是這個(gè)。
也就是說(shuō),如果我們構(gòu)造Handler時(shí),傳入Callback對(duì)象,則會(huì)執(zhí)行這個(gè)Callback中的handleMessage()方法,寫法如下:
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
}
//返回true,則不再回調(diào)Handler中的handleMessage方法。
return false;
}
});
返回值如果返回true,則不再回調(diào)Handler中的handleMessage方法。
如果為false,則會(huì)回調(diào)Handler中的handleMessage方法。
而我們平時(shí)常用的寫法:
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
相當(dāng)于繼承Handler,復(fù)寫了Handler的handleMessage()方法。也就是說(shuō)這是一個(gè)匿名內(nèi)部類。
但是這樣存在一個(gè)問(wèn)題。
由于Activity和Handler的生命周期不一致,如果子線程耗時(shí)操作還沒(méi)結(jié)束時(shí),我們把Activity關(guān)閉(finish)。因?yàn)檫@個(gè)時(shí)候耗時(shí)操作還沒(méi)結(jié)束,而匿名內(nèi)部類又持有外部類(Activity)的引用,所以這個(gè)時(shí)候Handler持有了Activity的引用。這就導(dǎo)致雖然Activity已經(jīng)finish()。但是內(nèi)存卻不能被回收,導(dǎo)致內(nèi)存泄漏。
所以一定要使用這種方式的話最好使用弱引用,否則應(yīng)該避免這種使用方式。
總結(jié)
最后我們總結(jié)一下Handler機(jī)制的流程:
1.構(gòu)造Looper,在主線程中不必手動(dòng)構(gòu)造,已經(jīng)存在Looper。
在子線程中需要使用Looper.perpar()構(gòu)造Looper,用Looper.myLooper()取得Looper,用Looper.loop()開(kāi)始循環(huán),用Looper.quit()終止循環(huán)。
2.在Looper的構(gòu)造方法內(nèi)部,會(huì)new一個(gè)MessageQueue,并儲(chǔ)存在Looper內(nèi)部
3.Looper構(gòu)造完成之后添加到ThreadLocal中
4.構(gòu)造Handler,在構(gòu)造方法中記錄該線程的Looper,Looper中的MessageQueue以及Callback
5.發(fā)送消息前,要構(gòu)造Message消息,如果用戶沒(méi)有傳入Message消息,則通過(guò)Message.obtain()從消息池中獲取一個(gè)Message。否則使用用戶傳進(jìn)來(lái)的Message。如果是使用Handler的post()方法發(fā)送消息,則把Runable賦值給Message的callback屬性。其他情況下,Message的callback屬性為null。最后一步,把Handler賦值給Message的target屬性。
6.Message構(gòu)造完成之后,調(diào)用第4步中記錄的MessageQueue將Message添加到消息隊(duì)列。
7.添加到消息隊(duì)列的Message會(huì)被Looper.loop()取出
8.從消息隊(duì)列獲取到Message后,調(diào)用msg.target.dispatchMessage(msg),也就是調(diào)用Handler的dispatchMessage()方法
9.dispatchMessage()方法根據(jù)用戶傳入的參數(shù),回調(diào)相應(yīng)的handleMessage()方法。