作過Android的都知道Message, MessageQueue, Handler和Looper,但知道不表明你理解它們。有時以爲用得很順手,但Android怎麼實現又說不上來,總以爲似懂非懂。不把它們攻破實在渾身不舒服。java
先讓咱們一句話總結,再開始分析。android
Looper不斷獲取MessageQueue中的一個Message,而後交給Hanlder處理。
其實Message和Runnable能夠一併壓入MessageQueue中,造成一個集合,後面將有所體現。app
本文所涉及的代碼文件以及路徑:async
frameworks/base/core/java/android/os/Hanlder.java
frameworks/base/core/java/android/os/Message.java
frameworks/base/core/java/android/os/MessageQueue.java
frameworks/base/core/java/android/os/Looper.java
frameworks/base/core/java/android/app/ActivityThread.java
frameworks/base/core/jni/android_os_MessageQueue.cpp
android.os.Message定義了消息必要的描述和屬性數據。ide
public final class Message implements Parcelable { public int what; public int arg1; public int arg2; public Object obj; public Messenger replyTo; Bundle data; Handler target; Runnable callback; ...... }
請注意裏面的target和callback,後面將對此進行關聯。其中arg1和arg2是用來存放整型數據的,what用來保存消息標識,obj是Object類型的任意對象,replyTo是消息管理器,會關聯到一個handler。一般Message對象不是直接new出來,只要調用handler中的obtainMessage方法來直接得到Message對象。這也是Android推薦的作法。函數
/** * Return a new Message instance from the global pool. Allows us to * avoid allocating new objects in many cases. */ public static Message obtain() { synchronized (sPoolSync) { if (sPool != null) { Message m = sPool; sPool = m.next; m.next = null; m.flags = 0; // clear in-use flag sPoolSize--; return m; } } return new Message(); }
你看,若是池中沒有才會new一個Message。oop
MessageQueue是一個final class,用來存放消息的消息隊列,它具備隊列的常規操做,包括:post
MessageQueue(boolean quitAllowed) { mQuitAllowed = quitAllowed; mPtr = nativeInit(); }
private native static long nativeInit();
由代碼能夠看出,由構造函數和本地方法nativeInit()組成。其中,nativeInit()會在本地建立一個NativeMessageQueue對象,而後賦給MessageQueue中的成員變量,這一系列經過內存指針進行。ui
static jlong android_os_MessageQueue_nativeInit(JNIEnv* env, jclass clazz) { NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue(); if (!nativeMessageQueue) { jniThrowRuntimeException(env, "Unable to allocate native queue"); return 0; } nativeMessageQueue->incStrong(env); return reinterpret_cast<jlong>(nativeMessageQueue); }
boolean enqueueMessage(Message msg, long when)
Message next()
void removeMessages(Handler h, Runnable r, Object object)
void removeMessages(Handler h, int what, Object object)
// Disposes of the underlying message queue. // Must only be called on the looper thread or the finalizer. private void dispose() { if (mPtr != 0) { nativeDestroy(mPtr); mPtr = 0; } }
銷燬隊列也須要用到本地方法,此處就不展開了。this
Handler做爲消息處理者,一是處理Message,二是將某個Message壓入MessageQueue中。Handler類中持有MessageQueue和Looper成員變量(後面再體現它們的做用):
public class Handler { final MessageQueue mQueue; final Looper mLooper; final Callback mCallback; final boolean mAsynchronous; IMessenger mMessenger; ...... }
先讓咱們focus Handler如何處理Message
public void dispatchMessage(Message msg)
public void handleMessage(Message msg)
一個對Message進行分發,一個對Message進行處理。
還記得開始的一句話總結麼?Looper從MessageQueue中取出一個Message後,首先會調用Handler.dispatchMessage進行消息分發。這裏雖然還沒涉及Looper的討論,但能夠先給出消息分發的代碼,具體在Looper類的loop方法中
public static void loop() { ...... for (;;) { ...... msg.target.dispatchMessage(msg); ...... } }
好,回到Handler的dispatchMessage方法
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
經過代碼得知,默認狀況下Handler的派發流程是:
其中mCallback爲
public interface Callback { public boolean handleMessage(Message msg); }
而通常狀況下,咱們就是經過直接new Handler的方式重寫handleMessage來處理Message,這個Handler就是消息處理責任人。
/** * Subclasses must implement this to receive messages. */ public void handleMessage(Message msg) { }
接着,Handler第二個做用是將某個Message壓入MessageQueue中。你們注意沒有,Message是Handler處理,而Message也是Handler壓入到MessageQueue中,既然這樣,爲何不直接執行?其實這樣是體現程序設計的有序性,若是事件優先級較小,就須要排隊,不然立刻處理。
將Message壓入到MessageQueue中,能調用的主要的方法有:
public final boolean post(Runnable r)
public final boolean postDelayed(Runnable r, long delayMillis)
public final boolean sendMessage(Message msg)
public final boolean sendEmptyMessage(int what)
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); }
post系列的方法會調用相應的sendEmptyMessage、sendEmptyMessageDelayed等方法,最終進入sendMessageAtTime中,而後調用enqueueMessage,把Message壓入隊列中。
因爲post方法的參數是Runnable對象,因此Hander內部提供了getPostMessage方法把Runnable對象轉化爲Message
private static Message getPostMessage(Runnable r) { Message m = Message.obtain(); m.callback = r; return m; }
最終,Handler造成了一個循環:Handler->MessageQueue->Message->Handler
Looper也是一個final class,而且持有一個MessageQueue,MessageQueue做爲線程的消息存儲倉庫,配合Handler, Looper一塊兒完成一系列操做。值得注意的是,還有一個final Thread和一個final ThreadLocal<Looper>的成員變量,其中ThreadLocal負責建立一個只針對當前線程的Looper及其它相關數據對象,其它線程沒法訪問。
Looper類中的註釋還給了一個使用Looper的普通線程範例:
/*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(); * } * } */
其實就是三個步驟:
看起來簡單吧?但是你能看出mHandler是怎樣把消息投遞到Looper所管理的MessageQueue中的麼?Looper在何時建立呢?
先看一下Looper.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)); }
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
首先經過sThreadLocal.get()判斷保證一個Thread只能有一個Looper實例,最後new Looper完成Looper的實例化。同時MessageQueue就在Looper的構造函數中建立出來。
再來看handler的建立。還記得前面提到的Handler類中的成員變量麼?Handler中就持有一個Looper,這樣一來,Handler就和Looper關聯起來了。Handler一共有7個構造函數,看其中一個:
public Handler(Callback callback, boolean async) { ...... 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; }
Looper中的myLooper()
public static @Nullable Looper myLooper() { return sThreadLocal.get(); }
這樣一來,Handler中的構造函數經過Looper.myLooper()獲取當前線程中的Looper實例,實際上就是Looper中的sThreadLocal.get()調用;而後把mLooper.mQueue賦給Handler的mQueue,最終Handler, Looper和MessageQueue就聯繫起來了。後續Handler執行post/send系列的方法時,會將消息投遞給mQueue,也就是mLooper.mQueue中。一旦Looper處理到消息,它又從中調用Handler來進行處理。
最後看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 Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg); 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(); } }
由前面得知,myLooper()就是調用sThreadLocal.get()來獲取與之匹配的Looper實例。me.mQueue驗證了每個Looper中都自帶了一個MessageQueue。進入for循環後,開始從MessageQueue中取出一個消息(可能會阻塞),若是當前消息隊列中沒有Message,線程退出;不然分發消息。msg.target.dispatchMessage(msg)中的target就是一個Handler。最後消息處理完畢,進行回收。
平時咱們在Activity中使用Handler處理Message時,爲何看不到Looper呢?這隻能說Android偷偷爲咱們作了一些背後的工做。好了,UI線程要上場了。
沒錯,ActivityThread就是咱們熟悉的UI線程,它在應用程序啓動的時候由系統建立出來。先來看一下這個UI線程的main函數
public static void main(String[] args) { ...... Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false); if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); } ...... Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }
有兩點與普通線程不同的地方。
普通線程只要prepare就能夠了,而主線程使用的是prepareMainLooper;普通線程生成一個與Looper綁定的Handler對象就行,而主線程是從當前線程中獲取Handler(thread.getHandler())。
public static void prepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } }
其實prepareMainLooper也是調用prepare,只是不讓該線程退出。通過prepare後,myLooper()就獲得一個本地線程<ThreadLocal>的Looper對象,而後賦給sMainLooper,也就是UI線程的Looper。若是其它線程想得到主線程的Looper,只需調用getMainLooper()。
public static Looper getMainLooper() { synchronized (Looper.class) { return sMainLooper; } }
再來看thread.getHandler()。
其實ActivityThead內部有一個繼承Handler的H類
private class H extends Handler { ...... public void handleMessage(Message msg) { ...... } ...... }
final H mH = new H();
因此thread.getHandler()返回的就是mH,這樣ActivityThread也有一個Handler處理各類消息了。
總結一下。
而Thread和Handler是一對多的關係。
到這裏,是否是對Message, MessageQueue, Handler和Looper有了更深的認識呢?
參考:
《深刻理解Android內核設計思想》 林學森 編著