- 基礎認識 Handler Message MessageQueue Looper
- Handler Message MessageQueue Looper 的關系
- 經(jīng)常碰上的問題(含解決方式)
基礎認識
Handler :主要用來子線程和主線程數(shù)據(jù)傳遞,更新UI。
Message:信息類,它可包含任意的數(shù)據(jù)傳給Handler。
MessageQueue:Message的消息隊列。
Looper :用于Message消息循環(huán)的一個類。
關系: 通過一個例子,結合源碼分析它們的工作流程。
以下是一個可運行的代碼,點擊Button,在Button事件中創(chuàng)建子線程,然后結合它們?nèi)ジ耣utton.setText的UI。
因為我要講得更細,而且語文能力有限,所以啰嗦點了。

從子線程中的run方法開始講。
27行:
通過Message.obtain(),handler.obtainMessage()去獲取Message實例,當然也可以new Message()獲取,推薦前兩種方式創(chuàng)建Message實例,以下源碼解釋說明,就是資源利用優(yōu)化問題。
* <p class="note">While the constructor of Message is public, the best way to get
* one of these is to call {@link #obtain Message.obtain()} or one of the
* {@link Handler#obtainMessage Handler.obtainMessage()} methods, which will pull
* them from a pool of recycled objects.</p>
30行:
用msg.what建立一個標識,還可以利用msg.setData(Bundle data)傳遞數(shù)據(jù)等等。前者方便在handleMessage里面區(qū)分事件處理情況。
31行:
handler.sendMessage(msg)是將Message放到消息隊列MessageQueue里面,但沒有處理消息的內(nèi)容。那么消息什么時候處理,接著看...
sendMessage源碼 依次點擊去里面的4函數(shù),最后到了jni層。
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);
}
---------------------------------------------------------------------------------------
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
第40行:
有一個表面意思翻譯就是處理Message消息的函數(shù)handleMessage(Message msg), 是時候引入Looper這個東西了。
來到這里我有幾個疑問:
Q 1. handleMessage(Message msg)在什么時候執(zhí)行里面的事件?
Q 2. 假設是Looper這個東西的里面有個事件讓handleMessage觸發(fā)事件,那看我最上面的例子,根本沒出現(xiàn)過Looper啊,我們也沒主動創(chuàng)建過Looper,究竟Looper是誰創(chuàng)建了?什么時候創(chuàng)建?
Q 3. 假設Looper已經(jīng)創(chuàng)建出來了,那是什么方法去觸發(fā)handleMessage執(zhí)行,什么時候啟動Looper里面那個我們還沒知道的方法?
不要急著一下全部解決,看我下面分析后再回想這幾個問題。
問題到這里必須得看源碼了。 上源碼~~
Tips:github上可以源碼 地址
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.java(6131行),你應該留意到了一句 Looper.prepareMainLooper(); 然后我再去找Looper這個類的prepareMainLooper()方法究竟是干嘛用的。 94~108行找到
/**
* 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) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
77~92 行
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
// True if the message queue can be quit.---quitAllowed
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.prepareMainLooper()調(diào)用了prepare(false)方法,而prepare(boolean quitAllowed)方法里面倒數(shù)第二行它創(chuàng)建了一個Looper并且將創(chuàng)建的這個Looper放到sThreadLocal(保存當前的Looper對象)里面。
這里解決了第二個問題!
Q: 誰創(chuàng)建的Looper,什么時候創(chuàng)建 -
A:系統(tǒng)自動在Activity啟動中ActivityThread里創(chuàng)建了Looper。
接著麻煩回去看ActivityThread.java的源碼,最后那幾行看到最后這個沒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;
}
// 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();
}
}
上面代碼所做的工作大概是
- 利用final Looper me = myLooper(); 找出當前的Looper。
- 通過final MessageQueue queue = me.mQueue;找出當前Looper有的MessageQueue。
(final MessageQueue mQueue,mQueue就是MessageQueue來的) - 最后就是msg.target.dispatchMessage(msg); msg就是Message,那么target是什么,在Message.java源碼中看到如下
/*package*/ Handler target;
那就清楚明白了,就是 調(diào)用了handler的dispatchMessage(msg)方法,那么它dispatchMessage又是干嘛的呢。 又在Handler.java源碼中找到
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
NICE 看到源碼中那個handleMessage(msg)沒,是不是好有成就感~~~
這里解決了第一和第三個問題!
Q:Looper里面哪個方法觸發(fā)handleMessage(msg),什么時候觸發(fā)那個方法(也就是觸發(fā)handleMessage(msg)方法)
A: 那個觸發(fā)handleMessage(msg)的方法就是loop(), 它是在Activity啟動中ActivityThread.java里面觸發(fā)的。
上面的已經(jīng)很好的介紹了Handler Message MessageQueue Looper,但是可能理解起來比較亂。下面整理下(還是跟著例子講):
- 子線程中創(chuàng)建了 Message,將需要傳遞的數(shù)據(jù)或者標識給Message。
- Message創(chuàng)建賦值完畢后就由handler中的snedMessage(msg)將Message塞到MessageQueue里面(做到這里只是單純的保存數(shù)據(jù),其它什么事都沒干)。
- 因為一個Activity啟動過程中,在ActivityThread里面的主函數(shù)里通過 Looper.prepareMainLooper()創(chuàng)建了默認的Looper,并且調(diào)用Looper.loop()把當前Looper中的MessageQueue消息通過dispatchMessage(msg)方法分發(fā)給handler中的handleMessage(msg)。
- 最后我們調(diào)用handleMessage(msg),在里面完成我們所需要的事件(如 例子中就是更新UI)。
而當中的第三步驟我們是看不到的,因為這是系統(tǒng)的機制。
經(jīng)常碰上的問題(含解決方式)
1. Can't create handler inside thread that has not called Looper.prepare()
直接在子線程里面創(chuàng)建一個Handler實施,然后調(diào)用handleMessage去更新UI。

Due to :在里面的線程里面沒有調(diào)用Looper.prepare()直接Crash。
Looper.prepare() 用來獲取Looper實例,雖然主線程是有默認的Looper實例,但是在子線程中它不會默認幫我們創(chuàng)建。但是為什么一定要Looper呢。
Tips: 怎樣比較快去找到所出現(xiàn)的問題在源碼的哪里,首先找對應的類先,然后里面直接搜索出現(xiàn)的錯誤原因:如這里直接search“Can't create handler inside thread that has not called Looper.prepare()”
public Handler() {
this(null, false);
}
-------------------------------------------------------------------------------------------
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;
}
看到上面源碼的中下可得知,因為在子線程里面不會自動創(chuàng)建Looper實例,Looper.myLooper()為null,所以導致拋異常。那為什么一定要創(chuàng)建Looper實例呢? 你留意下源碼mQueue = mLooper.mQueue;和 mCallback = callback;
mCallback的接口源碼如下: 它是調(diào)用handleMessage的
public interface Callback {
public boolean handleMessage(Message msg);
}
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
由此我們可以這樣理解:如果你沒Looper實例,那么你就獲取不到由Looper從MessageQueue分發(fā)出來的Message。那么Message都獲取不到,還處理消息handleMessage個毛啊!
好~~~那我就老老實實在new Handler之前添加Looper.prepare();

很好,程序順利運行成功,起碼不會crash先,但是我發(fā)現(xiàn)我點擊button 并沒有執(zhí)行handleMessage(Message msg)里面的所有事件。
噢噢~~我大概想到了,雖然我創(chuàng)建了Looper實例,但是我們不是還需要出發(fā)Looper里面的loop()函數(shù)的么,因為這函數(shù)會觸發(fā)msg.target.dispatchMessage(msg); 去分發(fā)Message給handler。SO~我再加個Looper.loop()給它咯。

咦~ 怎么還是不行的,添加Looper.loop()放在new Handler前后都不可以。WHAT ? WHAT ? WHAT ?
那是因為我根本就沒sendMessage,所以MessageQueue根本沒信息,那handle個毛???

加了 又錯 TT
2. Only the original thread that created a view hierarchy can touch its views.
它告訴我只能在主線程中更新UI的東西,這個也沒什么,因為我雖然是Looper.prepare()獲取到了Looper實例,而且觸動handleMessage,但是我依然是在子線里程更新UI了。
ViewRootImpl.java源碼 一直說更新UI只能在主線程,但是不知道為什么,看下面源碼
public ViewRootImpl(Context context, Display display) {
mContext = context;
mWindowSession = WindowManagerGlobal.getWindowSession();
mDisplay = display;
mBasePackageName = context.getBasePackageName();
mThread = Thread.currentThread();
mLocation = new WindowLeaked(null);
mLocation.fillInStackTrace();
mWidth = -1;
-----------------------------------------------------------------------------------------------
@Override
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
-------------------------------------------------------------------------------------------
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
requestLayout 是用來更新UI的,而里面的方法有個checkThread,mThread是指最初的主線程,因為Activity 在創(chuàng)建就新建了一個 ViewRootImpl 對象,所以是產(chǎn)生那個時候當前的Activity的主線程,而Thread.currentThread()就是當前執(zhí)行的線程了。
那么如果我想,我就喜歡在子線程里面new Handler去跟新UI,有沒有辦法呢,有!不過這樣做了沒什么意思吧了 哈哈。
方法:在new Handler時候,既然它那么喜歡主線程才能更新UI,那么我就通過Looper.getMainLooper()作為參數(shù)給它咯。

哎呀~~~ 我在添加Looper.prepare()時候,不小心添加多了一個喔,又creash
3. Only one Looper may be created per thread

繼續(xù)上源碼 Looper.java
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));
}
第一次我們Looper.prepare()之后,就new了一個Looper實例
Looper.java
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
-------------------------------------------------------------------------------------
ThreadLocal.java
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
這樣的話,sThreadLocal.get()就有了剛才創(chuàng)建的線程了,所以就Crash咯。
轉(zhuǎn)載請在開頭注明作者詳細信息和本文出處