提到Android裏的消息機制,便會提到Message、Handler、Looper、MessageQueue這四個類,我先簡單介紹如下這4個類
之間的愛恨情仇。java
消息的封裝類,裏邊存儲了消息的詳細信息,以及要傳遞的數據shell
主要用在消息的發送上,有即時消息,有延遲消息,內部還提供了享元模式封裝了消息對象池,可以有效的減小重複對象的建立,留更多的內存作其餘的事,app
這個類內部持有一個MessageQueue對象,當建立Looper的時候,同時也會建立一個MessageQueue,而後Looper的主要工做就不斷的輪訓MessageQueue,輪到天荒地老的那種less
內部持有一個Message對象,採用單項鍊表的形式來維護消息列隊。而且提供了入隊,出隊的基礎操做異步
舉個現實中的栗子,Message就至關於包裝好的快遞盒子,Handler就至關於傳送帶,MessageQueue就至關於快遞車,Looper就至關於快遞員,聯想一下,來個快遞盒子,biu丟到傳送帶上,傳送帶很智能,直接傳送到快遞三輪車裏,而後快遞小哥送一波~,日夜交替,不分晝夜的工做,好傢伙,007工做制async
好,咱們把這4個傢伙從頭到位分析一遍,要想使用Android的消息,首先要建立Looper對象,Android系統已經幫咱們在UI線程內建立好了一個,咱們能夠看一下ide
public final class ActivityThread extends ClientTransactionHandler { /** * The main entry point from zygote. */ public static void main(String[] args) { Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false, startSeq); 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
這個類你們應該不陌生吧,沒錯,他就是咱們App的主線程管理類,咱們看到他調用了 prepareMainLooper
來初始化,而後 loop
,天荒地老的那種loop,這個loop
,咱們最後聊函數
咱們看一下Looper內部提供的 prepareMainLooper
實現oop
public static void prepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } } 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(); }
上邊涉及到了3個方法,我都貼出來了,首先 quitAllowed
這個參數表明該Looper是否能夠退出,咱們主線程內的Looper是不容許退出的,因此封裝了 prepareMainLooper
方法和 prepare
方法已作區分,咱們項目中平時用的都是 prepare
方法,由於是子線程,因此容許退出Looper,你們在子線程內用完記得調用quit哦~
這裏咱們看Looper內部是經過ThreadLocal維護的Looper對象,也就是說每一個線程都是相互獨立的。並且Looper作了限制,每一個線程內部只能存在一個Looper對象,等同於每一個線程內只能有一個MessageQueue
最後在Looper的構造方法內,建立了一個MessageQueue對象,整個Looper的初始化就結束了ui
咱們準備好了Looper和MessageQueue後,就能夠建立消息啦,接下來咱們建立一個消息吧
//直接new對象,不推薦的方式 Message msg = new Message(); //推薦:內部是一個複用對象池 Message message = handler.obtainMessage(); message.what = 1; message.obj = "hello world";
咱們發送消息的時候,都是會藉助Handler的sendMessage就能夠把消息發送到列隊裏了,咱們往下看是如何完成的入隊操做吧,首先咱們平時都是建立一個Handler,而後調用sendMessage
就能夠了
Handler handler = new Handler(); handler.sendMessage(message);
咱們先看一下Handler的構造方法
public Handler() { this(null, false); } public Handler(@Nullable Callback callback, boolean async) { //FIND_POTENTIAL_LEAKS一直都是false,因此不用關心這個邏輯 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) { throw new RuntimeException( "Can't create handler inside thread " + Thread.currentThread() + " that has not called Looper.prepare()"); } //從Loopper內部獲取一個列隊 mQueue = mLooper.mQueue; // 回調對象,咱們平時寫的時候,通常都是用類集成的方式重寫 handleMessage 方法 mCallback = callback; //標示當前Handler是否支持異步消息 mAsynchronous = async; }
其實構造方法很簡單吶,就是獲取Looper對象,而後初始化列隊和回調對象就完事了,咱們繼續看sendMessage而後看消息的入隊吧
public final boolean sendMessage(@NonNull Message msg) { return sendMessageDelayed(msg, 0); } public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); } public boolean sendMessageAtTime(@NonNull 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); }
經過內部的重載方法,一直調用到sendMessageAtTime
方法,在這裏獲得Handler內部的MessageQueue
對象,而後調用了 enqueueMessage
方法準備入隊
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg, long uptimeMillis) { msg.target = this; msg.workSourceUid = ThreadLocalWorkSource.getUid(); if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
這裏調用了MessageQueue的enqueueMessage
方法真正入隊,咱們繼續看一下
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; //若是鏈表是空的,或者當前消息的when小於表頭的when的時候,便會從新設置表頭 //這裏能夠得知,消息的順序是按照延遲時間,從小往大排序的 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放到鏈表最後 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; }
經過這個方法,咱們瞭解到MessageQueue是經過Message的單鏈結構存儲的,而後每次入隊的時候,都會
經過這個enqueueMessage
方法向鏈表的最末尾添加數據。
最後咱們聊一下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(); // Allow overriding a threshold with a system prop. e.g. // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start' final int thresholdOverride = SystemProperties.getInt("log.looper." + Process.myUid() + "." + Thread.currentThread().getName() + ".slow", 0); boolean slowDeliveryDetected = false; for (;;) { //queue的next會阻塞 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); } // Make sure the observer won't change while processing a transaction. final Observer observer = sObserver; final long traceTag = me.mTraceTag; long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs; if (thresholdOverride > 0) { slowDispatchThresholdMs = thresholdOverride; slowDeliveryThresholdMs = thresholdOverride; } final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0); final boolean logSlowDispatch = (slowDispatchThresholdMs > 0); final boolean needStartTime = logSlowDelivery || logSlowDispatch; final boolean needEndTime = logSlowDispatch; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0; final long dispatchEnd; Object token = null; if (observer != null) { token = observer.messageDispatchStarting(); } long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid); try { //派發消息,執行回調handleMessage msg.target.dispatchMessage(msg); if (observer != null) { observer.messageDispatched(token, msg); } dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0; } catch (Exception exception) { if (observer != null) { observer.dispatchingThrewException(token, msg, exception); } throw exception; } finally { ThreadLocalWorkSource.restore(origWorkSource); if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (logSlowDelivery) { if (slowDeliveryDetected) { if ((dispatchStart - msg.when) <= 10) { Slog.w(TAG, "Drained"); slowDeliveryDetected = false; } } else { if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery", msg)) { // Once we write a slow delivery log, suppress until the queue drains. slowDeliveryDetected = true; } } } if (logSlowDispatch) { showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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(); } }
Looper內的loop方法別看這麼多,大多數都是日誌相關的處理。其實他就兩件事
第一件事就是從列隊中經過next
取出Message對象
第二件事就是經過Message對象上綁定的target對象dispatchMessage
方法,來分發消息
咱們接下來看一下dispatchMessage
方法,而後在看MessageQueue的next
public void dispatchMessage(@NonNull Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
灰常簡單,判斷CallBack對象。而後調用handleMessage就完事了,咱們的Activity就收到數據了。
接下來咱們看看MessageQueue的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) { 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; } }
首先MessageQueue的消息是用單鏈表的形式存儲,而後next函數作的事情就是死循環獲取消息,
在獲取消息的時候判斷一下消息是否符合執行時間,若是不符合執行時間,就進入睡眠狀態等待消息。
若是符合執行時間就直接返回Message給Looper進行分發,若是Message鏈表都爲空。則睡眠時間是-1
表明無休止的睡眠。在無休止睡眠的狀態下,enqueueMessage
的nativeWake
方法,會進行一次喚醒,喚醒後next
函數繼續執行,判斷返回消息給Looper執行消息分發