1. 程式人生 > >Android Handler和他的小夥伴們,訊息機制詳解

Android Handler和他的小夥伴們,訊息機制詳解

       Handler一直是面試很熱的話題,最近又看了好多文章,下面結合原始碼來總結一下。

       Handler 是Android 訊息機制的上層介面,Handler的執行需要底層的MessageQueue和Looper的支撐,他們是Handler的好基友。Handler的執行機制也就是Android的訊息機制。

       我們都知道Handler是用來更新UI的,其實更新UI只是開發者最常用的場景。概括來講:有時候需要在子線中進行耗時較長的I/O操縱,而I/O操作完成後需要在UI上做一些改變,這個時候可以通過Handler將更新UI的操作切換到主執行緒中去執行。這就是Handler的意義。

       那麼問題來了,主執行緒中可以使用Handler嘛?

檢視原始碼發現 在ActivityThread中是預設建立了主執行緒的Handler。

  回想一下,在第一次學習java時,我們都知道java需要Main方法才可以執行。 其實Main方法就在ActivityThread類中,
它是Android程式的啟動入口,也就是常說道的UI主執行緒。
static Handler sMainThreadHandler;  // set once in main()

public static void main(String[] args) {
               ........省略部分程式碼.......

        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        AsyncTask.init();

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
   可以發現
sMainThreadHandler是主執行緒的Handler。
   sMainThreadHandler = thread.getHandler();
final H mH = new H();
final Handler getHandler() {
        return mH;
}

而H是ActivityThread的一個內部類,是Handler的子類。

原始碼是這樣定義的:

 private class H extends Handler {
    。。。。省略內部程式碼。。。。。
 }

        所以主執行緒有自己的Handler,而且建立的時候通過呼叫 Looper.

prepareMainLooper()初始化了Looper,這就是主執行緒中預設可以使用Handler的原因。

        初步認識完了Handler,下面再介紹一遍他的小夥伴們。

        MessageQueue的中文翻譯是訊息佇列,顧名思義他的內部儲存了一組訊息。以佇列的形式對外提供插入和刪除的工作。雖然叫訊息對壘,但其實他的內部結構並不是真正的佇列,而是採用單鏈表的資料結構來儲存訊息列表。

        Looper的中文翻譯是迴圈,這裡可以理解問訊息迴圈。由於MassageQueue只是一個訊息的儲存單元,他不能處理訊息,而Looper正好填補了這個功能。Looper會以無限迴圈的形式在MessageQueue中查詢是否有新訊息。

        ThreadLocal是Looper中的一個特殊概念。它並不是執行緒,它的作用是可以在每個執行緒中儲存資料。我們知道Handler建立時會採用當前執行緒的Looper來構造訊息迴圈系統。那麼Handler內部如何獲取當前執行緒的Looper呢?這就是使用了ThreadLocal了,ThreadLocal可以在不同的執行緒中互不干擾的儲存並獲取資料。通過ThreadLocal可以輕鬆獲取每個執行緒的Looper。

       當然需要注意,執行緒是預設沒有Looper的,如果需要使用Handler就必須為執行緒建立Looper,我們上面提到的主執行緒使用 Looper.prepareMainLooper()也建立了自己Looper。在非UI執行緒中我們使用 Looper.prepareLooper()來建立當前執行緒的Looper。

我們順便分析一下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));
}
private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

通過上面的原始碼我們可以清晰的發現,Looper.prepareLooper()方法是建立了一個新的Looper,而且是依附當前對應的執行緒上。

同樣Looper.prepareMainLooper()是跟主線相對的Looper,也是建立了一個Looper例項。

        在Context類中可以通過getMainLooper方法得到主執行緒的Looper。

 public abstract Looper   getMainLooper();

那麼問題又來了,我在子執行緒中使用使用Looper.prepareLooper()建立Looper後能更新主執行緒的UI嘛?

比如:

public void run(){
     Looper.prepareLooper();
     Toast.makeText(MainActivity.this,"提示資訊",TOAST.LENGTH_SHORT).show();
     Message msg=new Message();
     loginHandler=new LoginHandler();
     loginHandler.sendMessage(msg);
     Looper.loop();
}

答案是不可以!會提示:

       Only the original thread that created a view hierarchy can touch its views. 
         原因:Looper.prepareLooper()方法會以當前執行緒為依附建立其Looper,如果換成另一種方式建立Handler
new Handler(Looper.getMainLooper())  ; 
這種方式是依附主執行緒上,是可以正常更新UI的。

接下來再來解釋一下MessageQueue。為什麼說它是單鏈表的資料結構?

MessageQueue主要包含兩個操作:插入和讀取。讀取操作本身會伴隨著刪除操作,

插入和讀取操作分別對應的方法為:(Message msg, long when)和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("MessageQueue", 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 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 (false) Log.v("MessageQueue", "Returning message: " + msg);
                        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("MessageQueue", "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 (;;) ,應該已經明白next()方法是一個無限迴圈的方法。如果訊息佇列中沒有訊息那麼next()方法就會一直阻塞在這裡。當訊息到來時,next方法會返回這條訊息並且將其從單鏈表中刪除。

        現在MessageQueue中有資料了,那麼Looper是怎麼來操作MessageQueue的呢?

        在Android的訊息機制中Looper主要扮演的是訊息迴圈的角色,具體來說就是它會不停的從MessageQueue中查詢是否有新的訊息。在Looper的構造方法中它會建立一個MessageQueue 即訊息佇列,並且將當前執行緒的物件儲存起來。

程式碼如下:

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

通過Looper.prepareLooper()建立了當前執行緒的Looper後,通過呼叫Looper.loop()來開啟訊息迴圈。也是Looper最重要的一個方法,只有呼叫了loop(),訊息迴圈系統才真正開始。

/**
     * 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;
            }
            // This must be in a local variable, in case a UI event sets the logger
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }
            msg.target.dispatchMessage(msg);
            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()方法的工作工程也比較好理解,loop方法是一個死迴圈,唯一跳出迴圈的方式是MessageQueue的next方法返回了null。

當Looper呼叫quit方式時

 /**
     * Quits the looper.
     * <p>
     * Causes the {@link #loop} method to terminate without processing any
     * more messages in the message queue.
     * </p><p>
     * Any attempt to post messages to the queue after the looper is asked to quit will fail.
     * For example, the {@link Handler#sendMessage(Message)} method will return false.
     * </p><p class="note">
     * Using this method may be unsafe because some messages may not be delivered
     * before the looper terminates.  Consider using {@link #quitSafely} instead to ensure
     * that all pending work is completed in an orderly manner.
     * </p>
     *
     * @see #quitSafely
     */
    public void quit() {
        mQueue.quit(false);
    }

        mQueue就是MessageQueue的例項。所以Looper.quit()是讓MessageQueue清空資料。

另外還有

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

         這裡傳入的boolean值是用來控制是否將當前狀態下訊息佇列中的方法執行完畢後再清空操作的。quitSafely就是在訊息要求執行完當前佇列中的所有訊息後,再做清空操作。從而Looper退出。

        而一般情況下不會呼叫quit方法。這個時候由於  MessageQueue.next(); // might block  在沒有訊息時處於阻塞狀態,從而Looper.loop()也處於阻塞狀態,等待訊息的到來。

        回過頭來,我們再從原點出發,Handler的主要工作過程是怎樣的?結合原始碼我們來看一下。

Handler 的主要工作包含,訊息的傳送和接收過程。訊息的傳送,可以通過post的一系列方法以及send的一系列方法來實現,post的一系列方法最終是通過send方法來實現的。

先看傳送過程吧。

      比如:

   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 sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

         可以看到了post方法裡面呼叫了相關的send方法。

         所有的send方法最終會呼叫enqueueMessage(queue, msg, uptimeMillis)方法。

    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;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

         enqueueMessage(queue, msg, uptimeMillis)是在最新建立的訊息佇列中的索引中中新增訊息,但是索引指向的地址mQueue塊是統一的,實際上說明一個Handler 對應一對MessageQueue、Looper。MessageQueue和Looper才是真愛,他們才是穿一個褲腿的好基友。而MessageQueue又是跟隨Looper而來的。換句話說MessageQueue是通過

  mLooper = Looper.myLooper();
  mQueue = mLooper.mQueue;

        或者mQueue = looper.mQueue;而來的。

        所以排位有了,大哥Handler,二哥Looper,三弟MessageQueue。任務就是把訊息這個唐僧送到西天去。

        可以發現,Handler傳送訊息的過程僅僅是向訊息佇列中插入了一條訊息。

        接下來MessageQueue的next方法就會返回這條訊息給Looper,Looper收到訊息後就開始處理了,最終訊息由Looper交由Handler處理,即Handler的dispatchMessage方法會被呼叫,這時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);
        }
    }

這裡handleMessage(msg)分兩種情況

mCallback不是null,mCallback就是前面傳過來的Ruannable方法。那麼呼叫

  /**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of Handler.
     *
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public interface Callback {
        public boolean handleMessage(Message msg);
    }

      如果mCallback為null,則呼叫

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

      除此之外還有handleCallback

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

       Message類中callback是這樣定義的:/*package*/ Runnable callback;

        怎麼這麼多Callback,我都凌亂了,請再次詳細檢視上面黑色斜體加粗字型。分清一個是方法一個是變數。mCallback實際上是一個介面。

    /**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of Handler.
     *
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public interface Callback {
        public boolean handleMessage(Message msg);
    }

       通過Callback可以採用如下方式來建立Handler物件:

Handler handler=new Handler(callback)。

       那麼callback的意義是什麼?

      通過Callback可以採用如下方式來建立Handler物件:

      Handler handler=new Handler(callback);

      原始碼裡面的註釋已經做了說明:可以用來建立一個Handler的例項但並不需要派生Handler的子類。在日常開發中,建立Handler最常見的方法是派生一個Handler的子類並重寫其handlerMessage方法來處理具體的訊息,而Callback給我們提供了另外一種使用Handler的方法,當我們不想派生子類時,就可以通過Callback來實現。

        前面我們提到ThreadLocal,日常開發中很少用到,但是在特殊情況下可以通過ThreadLocal輕鬆實現一些看起來比較複雜的功能。比如Looper、ActivityThread以及AMS(ActivityManagerService),研究ThreadLocal有助於我們更加深入的理解Handler。比如Handler需要獲取當前執行緒的Looper,很顯然Looper的作用域就是執行緒並且不同執行緒具有不同的Looper,這個時候通過ThreadLocal就可以輕鬆實現Looper線上程中的存取。概括來說:當某些資料是以執行緒為作用域並且不同執行緒需要獲取不同資料的副本的時候,就可以考慮使用ThreadLocal。

        如果Handler中不使用ThreadLocal,那麼系統就必須提供一個全域性的雜湊表供Handler查詢指定執行緒的Looper,這樣一來就必須提供一個類似LooperManager的類,但是系統並沒有這樣做而是選擇了ThreadLocal,這就是ThreadLocal的好處。