關(guān)于Android的消息處理機制,我們避免不了會提到Handler互妓,這也是面試常談的一個知識點,最近在整理相關(guān)資料坤塞,正好寫篇博客記錄下冯勉。
什么是Handler?
Handler是Andorid給我們提供的一套UI更新機制摹芙,同時它也是一套消息處理機制灼狰。
既然提到了消息處理機制,那么我們勢必會提到Handler浮禾、Looper交胚、MessageQueue、Message盈电,那么這幾個對象的存在有什么意義呢蝴簇?
Handler、Looper挣轨、MessageQueue军熏、Message之間的關(guān)系?
這里先簡單概述下它們的工作的流程卷扮,首先是創(chuàng)建Message信息荡澎,然后通過Handler發(fā)送到MessageQueue消息隊列均践,然后再通過Looper取出消息再交給Handler進(jìn)行處理。
為了幫助大家理解摩幔,大家可以這樣來想:
Handler是工人彤委,Message是產(chǎn)品,MessageQueue是傳送產(chǎn)品的傳送帶或衡,Looper是傳送帶的助力器焦影,整套流程下來就是,工人(Handler)把產(chǎn)品(Message)一個個的放入產(chǎn)品傳送帶(MessageQueue)封断,然后隨著傳送帶助力器(Looper)的推進(jìn)斯辰,再把產(chǎn)品一個個的取出處理。
想必這些問題你也曾遇到過吧坡疼?
記得剛學(xué)Android那會彬呻,知道耗時操作需要在子線程中完成,所以就創(chuàng)建了一個子線程來執(zhí)行網(wǎng)絡(luò)訪問柄瑰,當(dāng)訪問成功獲取數(shù)據(jù)更新UI的時候遇到:
Only the original thread that created a view hierarchy can touch its views
不能在非UI線程中更新視圖
后來了解到可以通過Handler把消息從子線程取出來并發(fā)送給主線程處理闸氮,就肆無忌憚的使用了,但在使用的過程中發(fā)現(xiàn)教沾,我們在主線程創(chuàng)建Handler的時候不會有問題蒲跨,但如果在子線程中創(chuàng)建Handler便會出現(xiàn)以下異常:
Can't create handler inside thread that has not called Looper.prepare()
不能在沒有調(diào)用Looper.prepare()方法的線程中創(chuàng)建Handler
那時候并沒有想太多,直接網(wǎng)上搜了下解決異常的方法授翻,就繼續(xù)往下寫了或悲,今天我們從源碼的角度來詳細(xì)的了解下為什么會有這些異常。
從源碼的角度帶你一步步分析
首先我們來看下創(chuàng)建Handler的過程藏姐,這是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;
}
我們只需要關(guān)注下面這幾行代碼:
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
在創(chuàng)建Handler的過程中隆箩,我們需要一個mLooper對象,如果它為空則會拋出上面所提到的異常
Can't create handler inside thread that has not called Looper.prepare()
那么這個Looper.myLooper();
做了什么操作呢羔杨?我們進(jìn)入方法中看個究竟:
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
它通過sThreadLocal變量的get方法從本地線程變量中獲取Looper對象,那么既然有g(shù)etter方法杨蛋,那一定也對應(yīng)著setter方法兜材,我們來看一下prepare()方法:
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));
}
原來在Looper類中的prepare方法中,我們對sThreadLocal變量設(shè)置了一個Looper對象逞力。
到這里我們可以總結(jié)出Handler的創(chuàng)建需要一個Looper對象曙寡,而這個Looper對象是在調(diào)用Looper.prepare()方法的時候創(chuàng)建的
這也解釋了為什么在子線程中,我們不能直接去創(chuàng)建Handler對象寇荧,而需要調(diào)用Looper.prepare()方法举庶,那么這里又引出一個問題,在主線程創(chuàng)建Handler的時候揩抡,并沒有執(zhí)行Looper.prepare()方法户侥,為什么不會報錯呢镀琉?這里我們依舊通過源碼來回答問題,我們找到ActivityThread類蕊唐,在類里我們找到main()方法:
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
ActivityThread代表Application的主線程屋摔,Android的入口方法就在ActivityThread類中的main方法,在這個方法里我們可以看到這么一行代碼:Looper.prepareMainLooper();
我們進(jìn)入方法看一下:
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
在方法里我們可以看到prepare(false);
(上文我們已經(jīng)提到替梨,在這個方法里會創(chuàng)建一個Looper對象钓试,并設(shè)置到sThreadLocal變量中)往下再通過 myLooper()取出。
所以這里我們可以知道副瀑,并不是主線程創(chuàng)建Handler不需要調(diào)用Looper.prepare()弓熏,而是系統(tǒng)內(nèi)部在創(chuàng)建主線程的時候就幫我們調(diào)用了。
現(xiàn)在我們繼續(xù)往下讀Handler的構(gòu)造方法糠睡,我們會發(fā)現(xiàn)這么一行代碼mQueue = mLooper.mQueue;
硝烂,說明我們在創(chuàng)建Looper消息線程的時候,它內(nèi)部會幫我們創(chuàng)建一個消息隊列铜幽,而這個消息隊列是用來存放Message對象的滞谢,既然有消息隊列,有消息除抛,那么肯定需要有入隊和出隊的操作狮杨,我們很自然的就會想到Handler是如何發(fā)送消息和處理消息的,Handler發(fā)送消息大致有兩種到忽,一種是sendMessage(Message msg)橄教,一種是post(Runnable r),追蹤源碼我們可以發(fā)現(xiàn)喘漏,不管是那種發(fā)送消息方式护蝶,它們最終調(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);
}
我們這里發(fā)現(xiàn)了enqueueMessage()方法翩迈,從字面上的意思可以知道這是一個消息入列的操作:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
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 {
// 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;
}
這里我們可以看到msg.target = this;
持灰,當(dāng)消息入列的時候,把自身(Handler)賦值給了target负饲,然后以時間的順序把這些需要處理的消息依次入列堤魁。
然后我們再來看下消息出列操作,這里我們回頭來看一下Looper類的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;
}
// 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 {
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();
}
}
在這里我們可以發(fā)現(xiàn)返十,消息線程Looper是個死循環(huán)妥泉,我們通過消息隊列next方法取出消息,當(dāng)消息為空的時候洞坑,消息線程會成阻塞狀態(tài)盲链,等待消息的到來,當(dāng)消息不為空的時候,會通過Looper發(fā)送對應(yīng)消息給Handler的dispatchMessage()方法進(jìn)行處理刽沾,這里的msg.target剛好就是上文提到的Handler(this)本慕,所以我們?nèi)andler類下找dispatchMessage方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
在這里我們可以看到,Handler在處理消息的時候悠轩,如果callback(Handler構(gòu)造方法里的mCallBack)不為空间狂,則在callback的handlerMessage處理消息,否則就在直接在Handler的handleMessage處理火架。
所以一個標(biāo)準(zhǔn)的異步消息處理線程應(yīng)該是這樣的:
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
最后補充幾個在子線程中更新UI的方法:
1鉴象、Handler的post()方法
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
2、View的post()方法
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
// Postpone the runnable until we know on which thread it needs to run.
// Assume that the runnable will be successfully placed after attach.
getRunQueue().post(action);
return true;
}
3何鸡、Activity的runOnUiThread()方法
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
經(jīng)過上面的源碼我們可以發(fā)現(xiàn)纺弊,其實本質(zhì)上都是調(diào)用了Handler.post()方法。
Handler使用不當(dāng)導(dǎo)致的內(nèi)存泄露骡男?
記得早期的android教材中(包括教科書)淆游,可能更多是想讓讀者先學(xué)會使用Handler,而沒有過多的去考慮內(nèi)存泄露這方面的事情隔盛,最常見的就是Handler以非靜態(tài)內(nèi)部類的方式存在犹菱,或者是持有外部Activity的強引用等,如:
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
tvUserName.setText("");
}
};
以上這些操作都很可能會導(dǎo)致內(nèi)存泄露吮炕,關(guān)于這方面的問題腊脱,改天專門寫一篇文章來說吧,就不再這里過多闡述了龙亲。
好了陕凹,到這里,關(guān)于Android的消息處理機制大致講完了鳄炉。