Handler源碼分析筆記

Handler

我們都知道Handler由Message、MessageQueueHandlerLooper組成,接下來我們帶著問題,從源碼中尋找 Handler 的具體流程與實現(xiàn)。

問題

  • 消息是如何發(fā)送出去的?
  • 消息時如何被得到的?
  • 輪詢器的啟動在什么時候?
  • 輪詢器與消息隊列的綁定是如何建立的?
  • 如何確??偸悄軌蛟趯?yīng)的線程中獲取到正確的輪詢器實例?
  • 對消息隊列的操作,消費者和生產(chǎn)者,主線程與子線程如何進(jìn)行通信?
  • Handler只能用于主線程UI更新?

解析

首先從輪詢器的啟動開始,所有的java程序都有一個main方法作為程序的入口,而Android中這個main方法在ActivityThread中

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

在代碼中我們可以看到 Looper.prepareMainLooper()和Looper.loop() 兩個方法

先從Looper.prepareMainLooper()進(jìn)行分析

    private static Looper sMainLooper;  // guarded by Looper.class 保存Looper類
    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,Looper將全局靜態(tài)變量 sMainLooper 賦值和調(diào)用了 prepare() 方法

    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    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));
    }
    //myLooper就是調(diào)用了sThreadLocal的get方法
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

在 prepare 中調(diào)用了全局靜態(tài)變量 sThreadLocal 的 set 方法

那么ThreadLocal是什么呢?

ThreadLocal本質(zhì)是一個Map,不過其中的 key 值是線程 Thread ,它通過線程來存儲和讀取數(shù)據(jù)。正如其名,用來存儲線程本地數(shù)據(jù)【避免其他線程讀取或修改】。

可就是說在此處,sThreadLocal 中存儲了與主線程對應(yīng)的 Looper 實例,只要是主線程中調(diào)用sThreadLocal 的get方法就能獲取這個輪詢器,若是其他子線程就獲取不到這個輪詢器

然后就到了講解 Looper.loop() ,也就是在這里開始死循環(huán),使得主線程一直存活

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;
    
        ...
            
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            ...

            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            try {
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            ...
            /*
            * 經(jīng)過上述步驟消息都未被處理,于是將其回收
            */
            msg.recycleUnchecked();
        }
    }

在 loop 中我們主要看到 MessageQueue 、 msg.target.dispatchMessage(msg) 這三處地方

我們先看 msg.target.dispatchMessage(msg) 之后,回來了解 MessageQueue

public final class Message implements Parcelable {
    ...
    Handler target;
    Runnable callback;
    ...
}

從 Message 中了解 target 就是 Handler,而 callback 是用戶設(shè)置的回調(diào)任務(wù),只要不設(shè)置這個 callback 就會進(jìn)入 handleMessage

public class Handler {
    ...
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //這里調(diào)用了用戶自定義的handleMessage去處理業(yè)務(wù)邏輯
            handleMessage(msg);
        }
    }
    ...
}

這里我們看到了消息時如何被得回應(yīng)的,那么我們只需要知道 Message 是怎么發(fā)送的和在什么時候給 target 賦值確保Handler對象不出錯。

Message 是如何發(fā)送的?這個問題想必都知道答案

public class Handler {
    final Looper mLooper;
    final MessageQueue mQueue;
    ...
    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
    
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
    //最終進(jìn)入該方法,此處就出現(xiàn)了 MessageQueue
    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) {
        msg.target = this;//在此處Handler給Message的target賦值
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
    ...
}

經(jīng)過一層一層的調(diào)用,最終Handler調(diào)用了 enqueueMessage 方法,將 Message 放入它的全局變量MessageQueue中,且將Message的target賦值為this【發(fā)送消息的Handler本身】

那么我們知道了發(fā)送的消息最終去向【MessageQueue】,那么Handler中的MessageQueue又是什么時候初始化的?

    //我們平常使用的Handler無參構(gòu)造函數(shù)最終都會到這里
    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());
            }
        }
        //此處就是為什么子線程不能創(chuàng)建Handler的原因
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

mLooper = Looper.myLooper() 之前我們分析過 myLooper 就是調(diào)用了sThreadLocal的get方法,此處只有主線程才有對應(yīng)的 Looper 實例存在,這也就是為什么子線程中不能用無參構(gòu)造方法實例化Handler,如果創(chuàng)建會報下列錯誤提示

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

當(dāng)然也不是沒有解決方案,不是沒有 Looper 報錯嗎,那就給唄?。?!解決方案

繼續(xù)向下,我們看到 mQueue = mLooper.mQueue ,也就是說 MessageQueue 是從Looper中獲取的

public final class Looper {
    private static Looper sMainLooper;  // guarded by Looper.class
    final MessageQueue mQueue;
    final Thread mThread;
    ...
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
    ...
}

嗯,MessageQueue 對象在私有構(gòu)造函數(shù)中就已經(jīng)實例化了,那么還記得什么時候調(diào)用了Looper的構(gòu)造函數(shù)嗎?

繞了一圈終于到了講解 MessageQueue 了

public final class MessageQueue {
    Message mMessages;//
    ...
    boolean enqueueMessage(Message msg, long when) {
        ...
        synchronized (this) {
            if (mQuitting) {//是否退出,只有調(diào)用了quit方法后是true
                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();
            //SystemClock.uptimeMillis() + delayMillis
            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ù)組或者List呢?因為 MessageQueue 采用鏈表的方式實現(xiàn)隊列。

public final class Message implements Parcelable {
    ...
    // sometimes we store linked lists of these things
    /*package*/ Message next;
    //最大Message池為50個
    private static final int MAX_POOL_SIZE = 50;
    ...
}

我們將 if 語句分開看

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

首先Message p被賦值為全局變量 mMessages【我稱其為“即將發(fā)送Message”】如果

  • “即將發(fā)送Message”是null
  • msg 的 when 是0 【when = SystemClock.uptimeMillis() + delayMillis】
  • msg 的 when 小于“即將發(fā)送Message”的 when 【 msg 發(fā)送事件的等待時間 小于 mMessages】

其中一個成立,將 msg 的 next 指向 p ,在將 mMessages 賦值為 msg【實際上就是將msg放在隊列最前面】

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

到else,基本就是 mMessages有值且 msg 發(fā)送事件的等待時間 大于 mMessages,于是就把 msg 放入鏈表中,通過循環(huán)將 msg 放入鏈表的合適位置,確保隊列中的元素等待時間是遞增的

既然已經(jīng)講了存放,那么就該到讀取了

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

                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.
                    //基本不會進(jìn)入這個if
                    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調(diào)用了 native 方法【就是java調(diào)用了c方法】,其具體的實現(xiàn)在 /frameworks/base/core/jni/android_os_MessageQueue.cpp 點擊此處查看

//可以理解為阻塞,ptr相當(dāng)于Message指針,timeoutMillis阻塞時間
private native void nativePollOnce(long ptr, int timeoutMillis); 
//喚醒,之前在enqueueMessage中有調(diào)用該方法喚醒
private native static void nativeWake(long ptr);

之后我們主要看 next 對 return 有關(guān)的部分

final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
//msg 對應(yīng)的 Handler 被銷毀,于是取出隊列中的下一個 Message
if (msg != null && msg.target == null) {
    do {
        prevMsg = msg;
        msg = msg.next;
    } while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
    //還沒有到 msg 的發(fā)送時間,需要阻塞等待
    if (now < msg.when) {
        // 下一條消息未準(zhǔn)備好。設(shè)置一個超時時間,當(dāng)它準(zhǔn)備好時喚醒。
        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
    } else {
        // 到 msg 的發(fā)送時間
        mBlocked = false;
        //將 mMessages 變?yōu)?msg 的 next
        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 {
    // nextPollTimeoutMillis = -1 代表nativePollOnce將一直阻塞直到被喚醒
    nextPollTimeoutMillis = -1;
}

到了這里Handler的源碼分析就結(jié)束了,可以再回去看看Handler的流程圖是不是會有新的感悟

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

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

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