從IntentService談Andoird消息分發機制

1、創建線程

2、在線程開始運行的時候,通過Looper.prepare() 創建消息隊列。中間涉及到ThreadLocal,保證了該線程只能有一個Looper和一個消息隊列。

3、然後Looper.loop(); 開始了無限循環模式,不斷從MessageQueue中獲取消息,然後調用Message的target 的dispatchMessage 處理消息。MessageQueue也在不斷的循環等待來新的消息,纔會返回到Looper中。

4、Message創建,可以從緩存中獲取已經處理的消息,或者創建新的對象

5、Handle 發送Message, 賦予Message的target值。 並且調用MessageQueue 的enqueueMessage 方法,按照Message.when順序插入到隊列之中。等待MessageQueue的next中無限循環獲取。

6、Looper.loop() 這個無限循環終於拿到了MessageQueue 返回的Message了, 調用Message.target.dispatchmessage方法, 也就是Handle的dispatchmessage 開始處理消息。

7、消息處理完成,Message.recycleUnchecked 放入緩存池,等待下次使用。



一、消息分發的關鍵類

Handler: 消息句柄,實現消息的發送和接收

Message: 消息對象

MessageQueue: 消息隊列,負責消息的管理

Looper: 負責從MessageQueue中不斷取出Message對象,實現分發

ThreadLocal: 保證了Looper在一個線程中只存在一個實例。


二、從IntentService分析消息分發


從IntentService源碼可以看出,內部主要靠 HandlerThread 實現線程的創建,和ServiceHandler實現任務在線程執行。

 @Override
    public void onCreate() {
       
        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); 
        thread.start();  //創建線程和消息隊列
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper); //創建Handler
    }
    @Override
    public void onStart(@Nullable Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }
    
     @WorkerThread
    protected abstract void onHandleIntent(@Nullable Intent intent);  // 處理消息


1、HandlerThread是如何創建消息隊列的?

HandlerThread 是一個包含 Looper 的 Thread,擁有自己的消息隊列。我們可以直接使用這個 Looper 創建 Handler。


HandlerThread其實就是Thread的子類,最終運行會調用到run方法。

@Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare(); //構建Looper
        synchronized (this) {
            mLooper = Looper.myLooper(); //獲取Looper
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();  
        Looper.loop(); //開始循環Loop
        mTid = -1;
    }
    


讓我們跟進 Looper.prepare()

    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"); //一個線程只能創建一個Looper實例
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }
    
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

可以看到創建了一個新的Looer對象,放到了sThreadLocal 這個靜態變量之中。

疑問:爲什麼要寫成靜態呢?

回答:爲了存儲Looper對象,保證一個線程只能創建一個Looper實例。


繼續深入,看看ThreadLocal 的set方法

    /**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's copy of
     *        this thread-local.
     */
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
    
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

大概意思可以看出,ThreadLocal其實是依據當前Thread線程,取出當前線程中,以ThreadLocal爲Key存儲的值。這裏就是Looper 了。

爲此,我們看看ThreadLocalMap

 /**
     * ThreadLocalMap is a customized hash map suitable only for
     * maintaining thread local values. No operations are exported
     * outside of the ThreadLocal class. The class is package private to
     * allow declaration of fields in class Thread.  To help deal with
     * very large and long-lived usages, the hash table entries use
     * WeakReferences for keys. However, since reference queues are not
     * used, stale entries are guaranteed to be removed only when
     * the table starts running out of space.
     */
    static class ThreadLocalMap {....
    
//從這段註釋中,可以理解ThreadLocalMap是一個自定義的HashMap,僅適用於存儲線程的本地值。
        /**
         * Construct a new map initially containing (firstKey, firstValue).
         * ThreadLocalMaps are constructed lazily, so we only create
         * one when we have at least one entry to put in it.
         */
        ThreadLocalMap(ThreadLocal firstKey, Object firstValue) {
            table = new Entry[INITIAL_CAPACITY];
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }


好,我們繼續回到HandlerThread中, 繼續run方法

 synchronized (this) {
            mLooper = Looper.myLooper(); //獲取Looper
            notifyAll();
        }

看看Looper.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();
    }
    
   // =====ThreadLocal.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();
    }
    /**
     * Variant of set() to establish initialValue. Used instead
     * of set() in case user has overridden the set() method.
     *
     * @return the initial value
     */
    private T setInitialValue() {
        T value = initialValue(); //返回null
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }
    
    protected T initialValue() {
        return null;
    }
    
    

從上面可以看出,Looper.myLooper() 就是爲了取出之前prepare()時候,依據當前線程創建的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;
            }
//...
            try {
                msg.target.dispatchMessage(msg);  //關鍵來了, 這裏處理了消息的分發
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
//...
            // 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();//放入緩存池
        }
    }

通過上訴代碼可以看到:msg.target.dispatchMessage(msg) 實現了最終的消息分發。

有個疑問?

如何實現的消息的等待,看源碼,一旦返回消息爲空,就退出了。帶着這個疑問,我們看看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) {
                        // 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;
        }
    }

從上訴代碼發現,當沒有消息的時候,一直for空轉循環等待。直到mQuitting爲true的時候,纔會退出。所以當我們自定義線程使用Looper,必須主動調用退出。


好,現在問題來了:

message 的 target是如何賦值的呢?

現在讓我們再回到IntentService中,看看serviceHandle的構建:

 HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");   //創建線程、Looper
 thread.start();  //Looper開始等待
 mServiceLooper = thread.getLooper();
 mServiceHandler = new ServiceHandler(mServiceLooper); // 這裏調用了Handle的構造方法


首先看看Handler的構造函數:

    public Handler(Looper looper) {
        this(looper, null, false);
    }
  
/**最終都會調用到以下構造函數
     * @hide
     */
    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

從以上代碼可以看出,Handler 屬性mLooper,mQueue,mCallback,mAsynchronous=false。

其中:mCallback 顧名思義,就是處理消息的回調,至於mAsynchronous=false ,常用幾個構造函數都是false,暫不考慮。

前面已經知道Looper、MessageQueue消息隊列。

繼續回到IntentService

 @Override
    public void onStart(@Nullable Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }

問題:

1、消息是如何創建的?

2、sendMessage 是如何將消息放入消息隊列的?


消息是如何創建的

查看Handler obtainMessage()源碼:

/**
     * Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
     * creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
     *  If you don't want that facility, just call Message.obtain() instead.
     */
    public final Message obtainMessage()
    {
        return Message.obtain(this);
    }
    
    #=====Message
    public static Message obtain(Handler h) {
        Message m = obtain();
        m.target = h;
        return m;
    }
    
    /**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     */
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

可以看到,最終從全局緩存池中獲取,沒有就創建一個。

問題:什麼時候會將Message放到緩存池?

前面Looper.loop 方法中可以看到,在消息分發處理完成後,就放入了緩存池。

  /**
     * Recycles a Message that may be in-use.
     * Used internally by the MessageQueue and Looper when disposing of queued Messages.
     */
    void recycleUnchecked() {
        // Mark the message as in use while it remains in the recycled object pool.
        // Clear out all other details.
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;
        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }


如何將消息放入消息隊列

handle.sendMessage

 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);
    }
 
 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; // 指定了target爲當前發送的Handler
        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;
            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;
    }


消息如何被處理

之前在Looper中已經看到,msg的target 也就是Handler處理了消息。

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

等等,mCallback是我們在Handler構造函數傳遞的,handleMessage, 也是處理消息的,msg.callback又是什麼呢?

再次進入到Message類中,發現msg.callback是一個Runnable, 做個假設,是不是Hander post的的這個Runnable呢? 看看源碼:

 /**
     * Causes the Runnable r to be added to the message queue.
     * The runnable will be run on the thread to which this handler is 
     * attached. 
     *  
     * @param r The Runnable that will be executed.
     * 
     * @return Returns true if the Runnable was successfully placed in to the 
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     */
    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;
    }

果然,上訴代碼驗證了我們的猜想。所以Handle在分發處理消息的時候,優先處理這個runnable, 然後再處理我們傳入的callback,最後纔是handleMessage。


綜上,整個消息的分發流程就分析完成。總結以下

三、總結

1、創建線程

2、在線程開始運行的時候,通過Looper.prepare() 創建消息隊列。中間涉及到ThreadLocal,保證了該線程只能有一個Looper和一個消息隊列。

3、然後Looper.loop(); 開始了無限循環模式,不斷從MessageQueue中獲取消息,然後調用Message的target 的dispatchMessage 處理消息。MessageQueue也在不斷的循環等待來新的消息,纔會返回到Looper中。

4、Message創建,可以從緩存中獲取已經處理的消息,或者創建新的對象

5、Handle 發送Message, 賦予Message的target值。 並且調用MessageQueue 的enqueueMessage 方法,按照Message.when順序插入到隊列之中。等待MessageQueue的next中無限循環獲取。

6、Looper.loop() 這個無限循環終於拿到了MessageQueue 返回的Message了, 調用Message.target.dispatchmessage方法, 也就是Handle的dispatchmessage 開始處理消息。

7、消息處理完成,Message.recycleUnchecked 放入緩存池,等待下次使用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章