一、簡介消息處理機制主要涉及到這幾個類:1.Looper2.MessageQueue3.Message4.Handler 二、源碼分析 Looper.class的關鍵源碼: 消息迴圈退出過程 從上面可以看到loop()方法是一個死迴圈,只有當MessageQueue的next()方法返回null時才 ...
一、簡介
消息處理機制主要涉及到這幾個類:
1.Looper
2.MessageQueue
3.Message
4.Handler
二、源碼分析
Looper.class的關鍵源碼:
//保存Looper對象,在android中每創建一個消息隊列,就有一個並且是唯一一個與之對應的Looper對象 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); //主線程的Looper private static Looper sMainLooper; //消息隊列 final MessageQueue mQueue; final Thread mThread; //子線程中通過調用該方法來創建消息隊列 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)); } //主線程調用該方法來創建消息隊列 public static void prepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } } //實例化Looper,創建消息隊列,獲取當前線程 private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); } //調用loop方法開啟消息迴圈 public static void loop() { //獲取當前的Looper對象,若為null,拋出異常 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; for (;;) { //調用next()方法從消息隊列中獲取消息,如果為null,結束迴圈;否則,繼續執行(有可能會阻塞) Message msg = queue.next(); if (msg == null) { return; } ...... try { //調用handler的dispatchMessage(msg)分發消息 msg.target.dispatchMessage(msg); } finally { ...... } //回收消息資源 msg.recycleUnchecked(); } } //消息迴圈退出 public void quit() { mQueue.quit(false); } public void quitSafely() { mQueue.quit(true); }
消息迴圈退出過程
從上面可以看到loop()方法是一個死迴圈,只有當MessageQueue的next()方法返回null時才會結束迴圈。那麼MessageQueue的next()方法何時為null呢?
在Looper類中我們看到了兩個結束的方法quit()和quitSalely()。
兩者的區別就是quit()方法直接結束迴圈,處理掉MessageQueue中所有的消息。
quitSafely()在處理完消息隊列中的剩餘的非延時消息(延時消息(延遲發送的消息)直接回收)時才退出。這兩個方法都調用了MessageQueue的quit()方法
MessageQueue.class 的關鍵源碼:
MessageQueue中最重要的就是兩個方法:
1.enqueueMessage()向隊列中插入消息
2.next() 從隊列中取出消息
/* *MessageQueue中enqueueMessage方法的目的有兩個: *1.插入消息到消息隊列 *2.喚醒Looper中等待的線程(如果是即時消息並且線程是阻塞狀態) */ boolean enqueueMessage(Message msg, long when) { //發送該消息的handler為null,拋出異常 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"); msg.recycle(); return false; } msg.markInUse(); msg.when = when; //消息隊列的第一個元素,MessageQueue中的成員變數mMessages指向的就是該鏈表的頭部元素。 Message p = mMessages; boolean needWake; if (p == null || when == 0 || when < p.when) { //如果此隊列中頭部元素是null(空的隊列,一般是第一次),或者此消息不是延時的消息,則此消息需要被立即處理, //將該消息作為新的頭部,並將此消息的next指向舊的頭部。如果是阻塞狀態則需要喚醒。 msg.next = p; mMessages = msg; needWake = mBlocked; } else { //如果此消息是延時的消息,則將其添加到隊列中, //原理就是鏈表的添加新元素,按照時間順序來插入的,這樣就得到一條有序的延時消息鏈表 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; prev.next = msg; } if (needWake) { nativeWake(mPtr); } } return true; } Message next() { //與native方法相關,當mPtr為0時返回null,退出消息迴圈 final long ptr = mPtr; if (ptr == 0) { return null; } int pendingIdleHandlerCount = -1; //0不進入睡眠,-1進入睡眠 int nextPollTimeoutMillis = 0; for (;;) { if (nextPollTimeoutMillis != 0) { //處理當前線程中待處理的Binder進程間通信請求 Binder.flushPendingCommands(); } //native方法,nextPollTimeoutMillis為-1時進入睡眠狀態 //阻塞方法,主要是通過native層的epoll監聽文件描述符的寫入事件來實現的。 //如果nextPollTimeoutMillis=-1,一直阻塞不會超時。 //如果nextPollTimeoutMillis=0,不會阻塞,立即返回。 //如果nextPollTimeoutMillis>0,最長阻塞nextPollTimeoutMillis毫秒(超時),如果期間有程式喚醒會立即返回 nativePollOnce(ptr, nextPollTimeoutMillis); synchronized (this) { final long now = SystemClock.uptimeMillis(); Message prevMsg = null; Message msg = mMessages; if (msg != null && msg.target == null) { 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 { //正常取出消息,設置mBlocked = false代表目前沒有阻塞 mBlocked = false; if (prevMsg != null) { prevMsg.next = msg.next; } else { mMessages = msg.next; } msg.next = null; 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); } } //非睡眠狀態下處理IdleHandler介面 for (int i = 0; i < pendingIdleHandlerCount; i++) { final IdleHandler idler = mPendingIdleHandlers[i]; // release the reference to the handler mPendingIdleHandlers[i] = null; boolean keep = false; try { keep = idler.queueIdle(); } catch (Throwable t) { Log.wtf(TAG, "IdleHandler threw exception", t); } if (!keep) { synchronized (this) { mIdleHandlers.remove(idler); } } } pendingIdleHandlerCount = 0; nextPollTimeoutMillis = 0; } }
Handler.class源碼分析:
/* *通過handler類向線程的消息隊列發送消息, *每個Handler對象中都有一個Looper對象和MessageQueue對象 */ 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()); } } //獲取Looper對象 mLooper = Looper.myLooper(); if (mLooper == null) {...} //獲取消息隊列 mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; } /* *多種sendMessage方法,最終都調用了同一個方法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); } /* *1.當Message中的callback不為null時,執行Message中的callback中的方法。這個callback時一個Runnable介面。 *2.當Handler中的Callback介面不為null時,執行Callback介面中的方法。 *3.直接執行Handler中的handleMessage()方法。 */ public void dispatchMessage(Message msg) { // 消息Callback介面不為null,執行Callback介面 if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { //Handler Callback介面不為null,執行介面方法 if (mCallback.handleMessage(msg)) { return; } } //處理消息 handleMessage(msg); } }