1. 程式人生 > >Android訊息機制原理解析

Android訊息機制原理解析

Android訊息機制:主要指Handler的執行機制以及Handler所附帶的MessageQueue和Looper的工作過程。

Handler:主要作用是將一個任務切換到指定的執行緒中去執行。Android中UI控制元件不是執行緒安全的,所以在Android中不允許子執行緒訪問UI,而當子執行緒需要訪問UI時,Android提供了Handler來解決這個問題。

MessageQueue訊息佇列:儲存訊息列表,內部儲存結構是單鏈表的資料結構

Looper迴圈:以無限迴圈的形式去查詢是否有新訊息,如果有就處理訊息,如果沒有就一直等待。

ThreadLocal的工作原理:

ThreadLocal是一個執行緒內部資料儲存類,通過它可以在指定執行緒中儲存資料,資料儲存以後,只有在指定執行緒中可以獲取到儲存的資料,對於其他執行緒則無法獲取到資料。
Handler為什麼要用到這個呢?因為對於Handler來說,需要獲取到當前執行緒的Looper,而Looper的作用域就是當前執行緒,並且在不同執行緒有不同的Looper,這個時候可以方便的通過ThreadLocal對Looper進行存取。
大概瞭解ThreadLocal後,下面分析下ThreadLocal的內部實現,ThreadLocal是一個泛型類,只要弄清楚ThreadLocal的get()和set()方法就可以明白它的工作原理。

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

set()方法中,首先是獲取到當前使用這個ThreadLocal物件的執行緒,然後根據當前執行緒獲取對應的ThreadLocalMap 物件,如果沒有ThreadLocalMap 物件,則建立一個,如果有則把資料存入ThreadLocalMap 物件中。
getMap()方法返回的是Thread.threadLocals,在Thread內部我們發現threadLocals變數是用來儲存ThreadLocal的資料,所以getMap()直接返回這個屬性,當該屬性為空時,通過createMap(t, value)來給Thread.threadLocals賦值。

    /* ThreadLocal values pertaining to this thread. This map is maintained by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

ThreadLocalMap類是ThreadLocal類的一個靜態內部類,在ThreadLocalMap內部有一個Entry[]陣列,ThreadLocal儲存的值就儲存在這個數組裡。Entry類是一個弱引用類,節省了記憶體。下面是table的儲存規則

 private void
set(ThreadLocal<?> key, Object value) { // We don't use a fast path as with get() because it is at // least as common to use set() to create new entries as // it is to replace existing ones, in which case, a fast // path would fail more often than not. Entry[] tab = table; int len = tab.length; int i = key.threadLocalHashCode & (len-1); for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) { ThreadLocal<?> k = e.get(); if (k == key) { e.value = value; return; } if (k == null) { replaceStaleEntry(key, value, i); return; } } tab[i] = new Entry(key, value); int sz = ++size; if (!cleanSomeSlots(i, sz) && sz >= threshold) rehash(); }

接下來看get()方法

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

get()方法仍然是通過當前執行緒獲取到ThreadLocalMap物件,然後獲取之前儲存的值,如果ThreadLocalMap物件為空,則使用預設值null

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

  protected T initialValue() {
        return null;
    }

從ThreadLocal的set 和get 方法,它們所操作的物件都是當前執行緒ThreadLocalMap物件的Entry[] table陣列,因此在不同執行緒中訪問同一個ThreadLocal的set 和get 方法,它們對ThreadLocal所做的操作僅限於各自執行緒的內部。這也是為什麼ThreadLocal可以在多個執行緒中互不干擾地儲存和修改資料。

MessageQueue工作原理

MessageQueue訊息佇列,主要包含兩個操作:插入和讀取。enqueueMessage(Message msg, long when)往訊息佇列中插入一條訊息,next()從訊息佇列中去除一條訊息並將其從訊息佇列中一處。

 boolean enqueueMessage(Message msg, long when) {

//判斷Message是否繫結一個Handler物件(msg.target)
        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) {

// 判斷該訊息是否正在退出,如果正在退出則回收當前訊息並返回false
            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; //第一次執行到這裡時,mMessages為null
            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;
//迴圈找到最後一個message
                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;
    }

next(),當訊息佇列裡有訊息時,則會取出這個message,即mMessages。當滿足條件時,則取出這個mMessages(通過Message msg = mMessages賦值後返回msg),然後把mMessages賦值為msg.next,即把下一個訊息賦值成mMessages。通過這個過程就把當前訊息處理完了,並且把處理過的訊息刪除掉了。

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

Looper的工作原理

Looper不斷地從MessageQueue中檢視是否有新訊息,如果有新訊息就立刻處理,否則就一直阻塞在哪裡。Looper的建構函式中建立了一個MessageQueue,並且儲存了當前執行緒。

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

Handler工作需要Looper,沒有Looper執行緒會報錯,那麼如何為一個執行緒建立Looper呢?其實通過Looper.prepare()就可以為當前執行緒建立一個Looper,接著通過Looper.loop()方法來開啟訊息迴圈。

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

prepare方法,就是把一個Looper物件儲存到了ThreadLocal

 public static void loop() {
//獲取當前執行緒的Looper物件
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
//把Looper物件繫結到MessageQueue
        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
//當MessageQueue為空時,則跳出迴圈loop結束
            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 {
//如果有訊息,則把這個訊息通過Handler(即msg.target)的dispatchMessage方法來處理這個訊息,這樣就成功將程式碼邏輯切換到制定執行緒中
                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 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();
        }
    }

上述通過prepare方法和loop方法只是對普通執行緒來說的,對於主執行緒來說,由於主執行緒情況比較複雜,所以提供了prepareMainLooper來給ActivityThread建立Looper物件,但是其本質也是通過prepare來實現的,這個可以自己去看原始碼。同時,也可以通過getMainLooper方法在其他任何地方獲取到主執行緒的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();
        }
    }

Handler的工作原理

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

send.pngpost.png

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

可以看出傳送訊息其實就是在MessageQueue中插入了一條訊息。MessageQueue的next()方法就會返回這條訊息給Looper,Looper接收訊息後就開始處理,最終訊息由Looper交由Handler處理,即呼叫Handler的dispatchMessage方法,這是Handler就進入處理訊息階段。

 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處理訊息過程;
首先檢查Messager的callback是否為null,,不為null就通過handleCallback來處理訊息。 message.callback是一個Runnable物件,實際上就是Handler的post方法所傳遞的Runnable物件。其次,檢查mCallback是否為null,不為null呼叫mCallback.handleMessage(msg)來處理訊息,最後,呼叫handleMessage來處理訊息。

總結

Android的訊息機制的總體流程就是:Handler向MessageQueue傳送一條訊息(即插入一條訊息),MessageQueue通過next方法把訊息傳給Looper,Looper收到訊息後開始處理,然後最終交給Handler自己去處理。換句話說就是:Handler給自己傳送了一條訊息,然後自己的handleMessage方法處理訊息,只是中間過程經過了MessageQueue和Looper。呼叫的方法過程如下:Handler.sendMessage方法–>Handler.enqueueMessage–>MessageQueue.next–>Looper.loop–>handler.dispatchMessage–>Handler.handleMessage(或者Runnable的run方法或者Callback.handleMessage)。