android消息處理機制

做過android開發的同學,相信對android的消息處理都不陌生。在我們開發應用中也是無時不刻不用到它,相信大家對handler的消息處理都能夠熟練使用了,那么本文將從源碼角度帶領讀者完成Handler,MessageQueue,Looper,ThreadLocal之間的聯系以及以及從消息發送到完成接收,系統為我們做了些什么。
handler相信大家都不陌生了,要完成線程間的消息通信一定會用到它,而使用handler無非是用到他的sendMessage或post方法,以及handleMessage回調。其實,在整個消息流中也確實是只有這些處理了。主要依賴的還是MessageQueue,Looper與handler之間的聯系。
在消息發送與消息處理完成,MessageQueue對于我們一直是不可見的,但我們卻必須用到它。MessageQueue作為消息隊列,顧名思義是用來存儲消息的。而MessageQueue作為消息隊列,主要完成消息的插入與刪除操作。即enqueueMessage與next方法:

  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;
}

通過enqueueMessage方法,將message插入到合適的位置,從這里我們可以看到,MessageQueue并非使用隊列作為消息存儲的,其實使用了單向鏈表的結構。
接下來我們看MessageQueue是如何獲取消息與刪除消息的:

 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) {
                    // 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 {
                    // 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;
    }
}

可以看到在next方法中,一開始就進入了一個死循環 for (;;),在循環中主要完成對message的查找并返回的操作,當MessageQueue為空時,那么就會一直處于block狀態,直到MessageQueue不為空或mQuitting為true.

分析完MessageQueue我們接下來看Looper,其實Looper在消息通信中主要扮演了消息循環的角色,這一點可以從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();
    }
}

在loop中仍然是進行了死循環操作 for (;;),在循環中不斷從獲取MessageQueue中獲取消息:
Message msg = queue.next();
唯一跳出循環的條件是msg == null。其實當我們調用Looper.quit()時,就是改變MessageQueue的mQuitting為true,使其返回null退出的。
當獲取到新消息時,會調用到
msg.target.dispatchMessage(msg);
而msg.target又是一個handler對象,咦,是不是有些熟悉呢?其實一點也沒錯,這里的handler就是我們一開始在代碼里面定義的handler,這一點可以在handler中找到:

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

不管你是通過send還是post方式,最終都會調用到這里的,不信自己可以去跟蹤下代碼。
接下來我們繼續跟蹤下msg.target.dispatchMessage(msg);方法

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

到這里我們又回到了handler方法中,又回到了最初的起點:這里會進行條件判斷,如果msg.callback不為null,處理handleCallback(msg),而msg.callback是我們通過handler的post方法傳進來的Runnable對象,這一點源碼中可以看到:

  public final boolean post(Runnable r)
{
   return  sendMessageDelayed(getPostMessage(r), 0);
}

繼續跟蹤getPostMessage(r)方法:

    private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

可以看到,通過getPostMessage方法,將Runnable對象賦給了Message的callback回調:
而handleCallback最終對調用到Runnalbe的run方法:

    private static void handleCallback(Message message) {
    message.callback.run();
}

而第二個判斷mCallback != null是作為構造參數傳給handler,是我們自己定義實現的callback回調;最后一種實現是handleMessage(msg);是一個空實現,是由我們自己繼承handleMessage(msg)來實現的。

到這里我們從消息發送到消息接收并處理整個流程都跑通了,是不是該結束了呢?
不,因為還有一個核心的東西我們還沒有提到,而它正是我們可以完成跨線程通信的核心機制,就是我們開始說到的ThreadLocal,ThreadLocal并不是本地線程,甚至連一個新線程也不算,為什么要叫ThreadLocal?他跟Thread有什么關系?這里我們要從Looper的生命周期開始看起:
在我們創建handler時,如果我們沒有在構造中傳入Looper,那么handler會在構造方法中初始化Looper.

    mLooper = Looper.myLooper();

在Looper.myLooper()中:

    public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}

這里調用到了sThreadLocal.get()方法,而sThreadLocal正是ThreadLocal對象,而在sThreadLocal.get()方法中:

    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();
}

這里用到了ThreadLocalMap類,主要用作數據存儲的,而在getMap(t)方法中,

    ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

返回了Thread的threadLocals對象,也是ThreadLocalMap的對象,其實ThreadLocalMap是用作數據存儲的,而ThreadLocalMap既是ThreadLocal的內部類,又是Thread的成員變量,不過通過ThreadLocal的set和get方法我們可以得知其實ThreadLocal操作的就是當前線程的ThreadLocalMap對象,通過調用Looper.parpare()為當前線程的ThreadLocalMap對象設置looper對象:

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));
}

在sThreadLocal.set(new Looper(quitAllowed))方法中:

    public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

當第一次創建Map時,

  void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}

將Looper對象最終傳給了當前線程的ThreadLocalMap對象并緩存,這就是為什么Looper和線程為什么可以綁定了,因為每一個Thread對應了一個Looper對象,當我們通過調用當前線程的Looper.parpare時,其實就已經將 Looper與當前線程綁定在了一起,而Looper持有了MessageQueue的引用,所以接下來的操作都綁定在了Looper所關聯的線程中了。所以handler處理消息回調時所在的線程并不一定是在handler的創建線程。

不信我們可以試試在子線程中創建handler,但在handler構造中傳入主線程的Looper,并在回調中打印當前線程名。

你發現規律了嗎?

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容