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