輕松而深入理解Android的消息機制之Handler運行機制

一提到Android的消息機制,相信各位看官一定會馬上聯(lián)想到Handler,Handler作為更新UI的神器之一,我們在日常開發(fā)中也就自然而然地會頻繁涉及這方面的內(nèi)容,今天在《輕松而深入理解Android的消息機制》系列第一篇中,我們就來梳理一下Handler的運行機制。

Handler的實際作用

我們大多數(shù)使用Handler都是為了去更新UI,但實際上Handler的功能不僅僅如此,更新UI也只是Handler的一個特殊使用場景。Handler的作用主要有兩個:
a.控制某個任務的開始執(zhí)行時間;
b.將某個任務切換到指定線程中執(zhí)行。

簡述Handler的運行機制

Handler運行機制實際上是Handler、Looper和MessageQueue三者共同協(xié)作的工作過程。
Looper:消息循環(huán),無限循環(huán)查詢是否有新消息處理,若沒有則等待。
MessageQueue:消息隊列,它的內(nèi)部存儲了一組消息,以隊列的形式對外提供插入和刪除工作,其只是一個消息的存儲單元,并不能去處理消息。
Handler創(chuàng)建時會采用當前線程的Looper,并獲取到Looper中的MessageQueue來構建內(nèi)部的消息循環(huán)系統(tǒng),若當前線程沒有Looper,則會拋出RuntimeException。Handler創(chuàng)建完畢后,當Handler的post方法或者send方法被調(diào)用時,Handler會將消息插入到消息隊列中,而后當Looper發(fā)現(xiàn)有新消息到來時,就會處理這個消息,最終消息的處理過程會在消息中的Runnable或者Handler的handleMessage方法中執(zhí)行。
為了便于理解,我們可以將上述過程類比為工廠的生長線,Handler是工人,負責產(chǎn)品的投放和包裝,Looper是發(fā)動機,一直處于開啟狀態(tài),MessageQueue是傳送帶,產(chǎn)品當然就是Message了。
此處上圖:


Android消息機制流程制圖.png

Handler的工作原理

Handler的工作主要包含消息的發(fā)送和接受過程。

Handler的創(chuàng)建

Handler有兩個構造方法需要留意一下:
a.當我們創(chuàng)建Handler時不傳入Looper時會調(diào)用此構造方法,從代碼中我們可以很輕易地找到在沒有Looper的子線程中創(chuàng)建Handler會引發(fā)程序異常的原因。

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

b.創(chuàng)建Handler時傳入Looper時會調(diào)用此構造方法

public Handler(Looper looper, Callback callback, boolean async) {
    mLooper = looper;
    mQueue = looper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

發(fā)送消息

消息的發(fā)送可以通過post的一系列方法以及send的一系列方法來實現(xiàn),post的一系列方法最終也是通過send的一系列方法來實現(xiàn)的,這里需要注意的是send方法傳入的是Message對象,而post方法傳入的是Runnable對象,而這個Runnable對象又會被存儲在msg.callback中。

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

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

從上面的流程圖中,我們可以清晰地看到無論是post方法還是send方法最終都會調(diào)用enqueueMessage方法,而從代碼也可以看出,Handler發(fā)送消息的過程僅僅是向隊列中插入一條消息的過程。

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) {
    // 這里需要特別注意,將當前Handler保存于Message.target中
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

接收消息

Handler向隊列中插入一條消息后,最后會經(jīng)過Looper處理交由Handler處理,此時Handler的dispatchMessage方法會被調(diào)用。

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

在dispatchMessage方法中,首先看msg.callback != null,msg.callback似曾相識啊,沒錯,前面提到了調(diào)用post方法時傳入的Runable對象會存儲在Message.callback中,handleCallback的邏輯如下:

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

在Handler類中,有一個接口類Callback,實現(xiàn)這個接口需要實現(xiàn)handleMessage(Message msg)方法,這個類到底有什么用呢?我們都知道Handler類中有一個空方法handleMessage(Message msg) ,所有Handler的子類必須實現(xiàn)這個方法,而Callback的存在也就使得當我們需要創(chuàng)建一個Handler的實例時,我們就不必再派生Handler的子類了。

/**
 * Subclasses must implement this to receive messages.
 */
public void handleMessage(Message msg) {
}

final Callback mCallback;
public interface Callback {
    /**
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public boolean handleMessage(Message msg);
}

梳理完了Handler的工作原理,接下里再來分析Looper的工作原理。

Looper的工作原理

Looper在Android的消息機制中扮演著消息循環(huán)的角色,它會不停地從MessageQueue中查看是否有新消息,如果有新消息就會立刻處理,否則就一直阻塞在那里。

Looper的創(chuàng)建

在Looper的構造方法中,Looper創(chuàng)建一個MessageQueue,并且保存了當前線程。

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

我們知道Handler的工作需要Looper,而線程默認是沒有Looper的,所以在沒有Looper的線程中我們需要通過Looper.prepare()方法為當前線程創(chuàng)建一個Looper,在Looper被創(chuàng)建的同時會將自己保存到自己所在線程的threadLocals變量中。

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<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));
}

ThreadLocal<T>

ThreadLocal是一個線程內(nèi)部的數(shù)據(jù)存儲類,其最大的作用在于可以在多個線程中互不干擾地存儲和修改數(shù)據(jù),這也是解決多線程的并發(fā)問題的思路之一。當不同線程訪問同一個ThreadLocal的get方法,ThreadLocal內(nèi)部會從各自的線程中取出一個數(shù)組,然后再從數(shù)組中根據(jù)當前ThreadLocal的索引去查找出對應的value值。
ThreadLocal實際上是一個泛型類,其定義為public class ThreadLocal<T>,在Thread類內(nèi)部有一個成員專門用于存儲線程的ThreadLocal的數(shù)據(jù):ThreadLocal.ThreadLocalMap threadLocals。

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

public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

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

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

private T setInitialValue() {
    T value = initialValue();
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
    return value;
}

loop()

這個方法是Looper類中最重要的一個方法,只有在調(diào)用loop方法后,消息循環(huán)系統(tǒng)才會真正地啟動。
loop方法首先會獲取當前線程所保存的Looper對象和MessageQueue對象,然后調(diào)用MessageQueue的next方法來獲取新消息,而next是一個阻塞操作,當沒有消息時,next方法會一直阻塞在這里。當MessageQueue的next方法返回null時,loop的死循環(huán)會跳出。當MessageQueue的next返回新消息時,Looper就會處理這條消息,即msg.target.dispatchMessage(msg),在Handler的enqueueMessage方法可以看到,msg.target實際上就是發(fā)送這條消息的Handler對象,因此Handler發(fā)送的消息最終就還是交給了其dispatchMessage方法來處理,此時Handler的dispatchMessage方法是在創(chuàng)建Handler時所使用的Looper中執(zhí)行的,也就成功將代碼邏輯切換到指定的線程中去執(zhí)行了。

/**
 * Return the Looper object associated with the current thread.  Returns
 * null if the calling thread is not associated with a Looper.
 */
public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}

/**
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the 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;
        }

        ...

        final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        final long end;
        try {
            msg.target.dispatchMessage(msg);
            end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        ...

        msg.recycleUnchecked();
    }
}

quit()和quitSafely()

在子線程中,若手動為其創(chuàng)建了Looper,則在所有的事情處理完成后應調(diào)用quit方法來終止消息循環(huán),否則此線程會一直處于等待狀態(tài)。
quit()會直接退出Looper,quitSafely()只是設定一個退出標記,待消息隊列已有消息處理完畢后再安全退出。

public void quit() {
    mQueue.quit(false);
}

public void quitSafely() {
    mQueue.quit(true);
}

MessageQueue#quit
void quit(boolean safe) {
    if (!mQuitAllowed) {
        throw new IllegalStateException("Main thread not allowed to quit.");
    }

    synchronized (this) {
        if (mQuitting) {
            return;
        }
        mQuitting = true;

        if (safe) {
            removeAllFutureMessagesLocked();
        } else {
            removeAllMessagesLocked();
        }

        // We can assume mPtr != 0 because mQuitting was previously false.
        nativeWake(mPtr);
    }
}

Looper的工作原理就分析到這里了,下面我們再來看看MessageQueue的工作原理

MessageQueue的工作原理

MessageQueue的內(nèi)部存儲結構并不是真正的隊列,而是采用單鏈表的數(shù)據(jù)結構來存儲消息隊列,單鏈表在插入和刪除數(shù)據(jù)上是比較有優(yōu)勢的。
MessageQueue主要包含兩個操作:插入和讀取。讀取操作本身會伴隨著刪除操作,插入和讀取對應的方法分別為enqueueMessage和next,其中enqueueMessage的作用是往消息隊列中插入一條消息,而next的作用是從消息隊列中取出一條消息并將其從消息隊列移除。

插入數(shù)據(jù):enqueueMessage()

上邊提到過,Handler的enqueueMessage方法會向MessageQueue插入數(shù)據(jù),此時MessageQueue的enqueueMessage方法會被調(diào)用,從代碼可以看到,enqueueMessage的要操作實質上就是單鏈表的插入操作。
這里提一下mQuitting這個布爾變量,當消息循環(huán)退出時(MessageQueue的quit()方法被調(diào)用時),mQuitting的值為true,此后通過Handler發(fā)送的消息都會返回false,也就是我們所說的發(fā)送失敗。

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

讀取數(shù)據(jù):next()

next是一個無限循環(huán)的方法,如果消息隊列中沒有消息,next會一直阻塞在這里;當有新消息時,next會返回這條消息并將其從單鏈表中移除。
當mQuitting值為true時,next方法會返回null,即Looper.loop方法跳出了死循環(huán)。

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

到這里,Handler的運行機制的基本流程也就介紹完畢了,最后再來簡單說一下主線程的消息循環(huán)。

主線程的消息循環(huán)

上面提到過,Handler的使用必須需要在當前線程中創(chuàng)建Looper,然而在實際開發(fā)中,我們在主線程使用Handler時卻沒有創(chuàng)建Looper,這是因為主線程在被創(chuàng)建時就會初始化了Looper,所以主線程中是默認可以使用Handler的。
大家都知道Android的主線程就是ActivityThread,主線程(UI線程)的入口方法為main,在main方法中系統(tǒng)會通過Looper.prepareMainLooper()來創(chuàng)建主線程的Looper以及MessageQueue,并通過Looper.loop()來開啟主線程的消息循環(huán)。此后Looper會一直從消息隊列中取消息,然后處理消息。用戶或者系統(tǒng)通過Handler不斷地往消息隊列中插入消息,這些消息不斷地被取出、處理、回收,使得應用迅速地運轉起來。

public static void main(String[] args) {
    ...
    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");
}

Looper#prepareMainLooper
public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}

這就是本篇文章的全部內(nèi)容了,在下一篇中我們還會繼續(xù)梳理一下和Android消息機制相關的其他知識。由于本人的能力和水平有限,難免會出現(xiàn)錯誤,如有發(fā)現(xiàn)還望大家指正。

參考書籍:《Android開發(fā)藝術探索》

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容