從原始碼去理解Handler

小白龍丶發表於2019-03-28

前言


handler是所有Android工程師都十分常用的工具,功能豐富,既可以用於執行緒間的訊息傳遞、元件間通訊,也可以實現定時任務、重複任務。本文將從原始碼角度理解handler的實現。

  • 1.handler的建立

//frameworks/base/core/java/android/os/Handler.java
//建立方法1
Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //do Something
            }
        };
      
//建立方法2  通常用於子執行緒中操作UI時使用  傳入主執行緒的loop  
Handler handler = new Handler(Looper.getMainLooper());
複製程式碼

除了上面兩種建立方式之外handler還有好幾種構造方法,但是最終呼叫的只有如下兩個方法。

//frameworks/base/core/java/android/os/Handler.java
//上面建立方法1最終所呼叫的方法
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());
            }
        }

        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;
    }
    
//上面建立方法2最終所呼叫的方法
public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

複製程式碼

可以看到帶有loop的構造方法大致只是做了一個賦值,其中loop是傳入的已存在的looper,callback是Handler中的一個interface。

//frameworks/base/core/java/android/os/Handler.java
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);
    }
    
/**
 * Subclasses must implement this to receive messages.
 */
public void handleMessage(Message msg) {
    }
    
/**
 * Handle system messages here.
 */
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

private static void handleCallback(Message message) {
        message.callback.run();
    }
複製程式碼

可以看到在Handler在處理msg的時候首先判斷msg裡面的callback是否為空,不為空就直接handleCallback了,為空再走callback的handleMessage和Handler本身的成員方法handleMessage,再看handleCallback方法,是不是恍然大悟,我們常用的handler.post(Runnable r)方法。我們在原始碼裡再驗證下我們的想法。

//frameworks/base/core/java/android/os/Handler.java
//handler中的post方法
public final boolean post(Runnable r)
{
   return  sendMessageDelayed(getPostMessage(r), 0);
}
//通過Message.obtain()拿到了Message物件m,並將r賦值給m.callback
private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}
複製程式碼

終於到最後一個引數了,async,中文是非同步的。看看賦值之後在哪裡被使用

//frameworks/base/core/java/android/os/Handler.java
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
複製程式碼

最終還是到了Message身上,msg.setAsynchronous(true);設定message是否是非同步的,這是message的一個屬性。同一個Thread只有一個Looper,一個MessageQueue,但是可以有很多個Handler,如果Handler初始化的時候async引數是true,那麼這個Handler所post的所有的message都會帶上非同步的屬性。可以通過MessageQueue的postSyncBarrier(long when)來向佇列中插入一個同步分割欄,同步分割欄是一個特殊的message,這種message的target=null,就像一個卡子,當他被插入時,會卡住在這之後的所有的同步的message,只會摘取非同步的message。當然也可以通過MessageQueue的removeSyncBarrier(int token)來移除這個同步分割欄,token就是postSyncBarrier方法的返回值。但是目前這兩個方法都被hide了。所以大家一般用到的都只是普通的Message。

到現在終於可以看一眼比較複雜的建立方法1了。

//frameworks/base/core/java/android/os/Handler.java
//上面建立方法1最終所呼叫的方法
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());
            }
        }

        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;
    }
複製程式碼

第一個if,找到潛在的洩漏,看看判斷的條件,是否是匿名內部類、成員內部類、區域性內部類並且不是static。想想看,有點意思,Java的特性:非靜態的內部類和匿名內部類都會隱式的持有一個外部類的引用,所以這才是導致可能發生記憶體洩漏的關鍵,在我們日常程式設計中要注意這點,不然很可能會GG。繼續往下,由於沒有傳Looper進來,所以拿到自己的Looper,這裡可能丟擲一個異常,大家應該遇到過,當你在一個新的執行緒中使用handler的時候,要先Looper.prepare(),不然就會丟擲上面的異常,我們再去看下Looper.prepare()幹了啥。

//frameworks/base/core/java/android/os/Looper.java
    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));
    }

    /**
     * Initialize the current thread as a looper, marking it as an
     * application is main looper. The main looper for your application
     * is created by the Android environment, so you should never need
     * to call this function yourself.  See also: {@link #prepare()}
     */
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
    
    /**
     * 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();
    }
複製程式碼

可以看到就是新建了一個Looper然後設定到了sThreadLocal中,其中new Looper(quitAllowed)時傳入了一個引數quitAllowed。

//frameworks/base/core/java/android/os/Looper.java
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
    
//frameworks/base/core/java/android/os/MessageQueue.java
  MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();
    }
    
    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);
        }
    }
複製程式碼

可以看到這個引數控制這MessageQueue是否可以清空,如果呼叫了quitAllowed=true的Looper的quitSafely()方法,將清空所有Message,並且拒絕接收新的Message。prepareMainLooper()方法中quitAllowed引數為false,所以我們沒辦法讓主執行緒的MessageQueue清空並拒絕插入Message,這也符合Android主執行緒的設計。

  • 2.handler傳送Message

//frameworks/base/core/java/android/os/Handler.java
    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
    
    public final boolean postAtTime(Runnable r, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r), uptimeMillis);
    }
    
    public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
    }
    
    public final boolean postDelayed(Runnable r, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }
    
    public final boolean postAtFrontOfQueue(Runnable r)
    {
        return sendMessageAtFrontOfQueue(getPostMessage(r));
    }

    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

    public final boolean sendEmptyMessage(int what)
    {
        return sendEmptyMessageDelayed(what, 0);
    }

    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }

    public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageAtTime(msg, uptimeMillis);
    }
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

    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);
    }
    public final boolean sendMessageAtFrontOfQueue(Message msg) {
        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, 0);
    }
複製程式碼

上面是所有Handler傳送訊息的方法,不管是什麼方法,最終都是來到了enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)方法。

//frameworks/base/core/java/android/os/Handler.java
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
    
//frameworks/base/core/java/android/os/MessageQueue.java
    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 do not 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;
    }
複製程式碼

可以看到第一個方法中 msg.target = this;將當前Handler賦值給了msg.target,這是區分由哪個handler處理的關鍵。再看Message Queue中的方法,首先判斷msg的target是否為空以及當前msg是否已經被使用,接著一個大的synchronized塊,首先判斷mQuitting的值,如果true則釋放這個message並且return false。mQuitting這個值的設定就在在之前MessageQueue的quit(boolean safe),這裡也說明了一旦呼叫了這個方法,MessageQueue則不會再接收任何訊息。接下來第一個if的判斷,p == null代表當前沒有要處理的Message、when == 0代表立馬插入、when < p.when代表傳入msg的when比當前要處理的Message的時間還要提前,所以滿足上面的條件之一的都會被插入到訊息佇列的首部。那下面else部分就是判斷傳入的msg該插入到佇列中的哪個部分,裡面的for迴圈就是完成了這麼一件事情。但是其中有個needWake,字面意思是需要被喚醒,兩個賦值的地方:if塊裡 needWake = mBlocked,直接賦值,如果當前狀態是blocked,需要喚醒,沒毛病。 else塊裡needWake = false,如果需要喚醒並且p是非同步的,注意一點能走到這裡的代表p不是第一個訊息。說明即便msg是非同步的,也不是連結串列中第一個非同步訊息,所以沒必要喚醒了。

  • 3.Message的處理

在前面只說到了Message被插入到了訊息佇列中,那麼Message又是怎麼被取出來,又是怎麼處理的呢,上面絲毫未提,但是回想一下,我們在Looper.prepare()之後是不是有個必做的方法Looper.loop()。看來應該都在這裡面了。

//frameworks/base/core/java/android/os/Looper.java
    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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            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);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread was not 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();
        }
    }
複製程式碼

大部分都是Log,可以看到一個死迴圈,通過Message msg = queue.next(),拿到了要處理的msg,這個next()可能會引起中斷,通過 msg.target.dispatchMessage(msg);實現了處理。msg.target就是之前設定進去的handler,所以就是呼叫handler的dispatchMessage,這個方法已經在上面分析過了。那麼現在就簡單了,我們看下MessageQueue的next()方法。

//frameworks/base/core/java/android/os/MessageQueue.java
    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;
        }
    }
複製程式碼

看這程式碼,不出所料(沒有其他可能了) nativePollOnce(ptr, nextPollTimeoutMillis);這句就是中斷用的了,然後我們看第一個地方,msg != null && msg.target == null,是不是同步分割欄,看程式碼,如果當前的msg是同步分割欄,那麼就找到後面是有非同步屬性的msg。第二個地方,首先判斷msg應該執行的時間,有dealy就計算delay的時間,delay最大不超過Integer.MAX_VALUE。沒有delay就拿到了msg,就直接return回去了。第三個方法說明此時已經沒了msg,nextPollTimeoutMillis= -1,當執行nativePollOnce時就代表一直阻塞。第四個地方說明呼叫了quit()方法,丟棄msg並返回空。第五個地方,看註釋,如果第一次空閒,則獲取要執行的idlers數量。僅當佇列為空或第一條訊息在佇列中(可能是屏障)將在將來處理。要是沒有要執行的就直接設定mBlocked為true,然後continue了,接著就阻塞了。然後把mIdleHandlers拷貝到mPendingIdleHandlers裡,就到了第六個地方,就開始執行idler.queueIdle()了,根據idler的返回值判斷要不要從mIdleHandlers中移除,如果不移除那麼以後每次空閒都就會執行。第七個地方,將pendingIdleHandlerCount賦值為0,避免再執行(在這一次的MessageQueue的next()方法中最多隻執行一次)。將nextPollTimeoutMillis賦值為0,因為不知道在所有的mIdleHandlers都執行完成之後msg的when到了沒了,所以設定成0,直接再來一次,看到這裡終於理解如何利用handler來做延遲載入了,其間奧祕全在mIdleHandlers裡。

基本上Handler就到這裡結束了,可還行

相關文章