Handler 機制再瞭解

fitzeng發表於2017-09-12

這裡主要是先了解整個訊息傳遞的過程,知道這樣做的好處和必要性。而不是直接介紹裡面的幾個關鍵類,然後介紹這個機制,這樣容易頭暈。而且網路上已經有很多這樣的文章了,那些作者所站的高度對於我這種初學者來說有點高,我理解起來是比較稀裡糊塗的,所以這裡從一個問題出發,一步一步跟蹤程式碼,這裡只是搞清楚 handler 是怎麼跨執行緒收發訊息的,具體實現細節還是參考網上的那些大神的 Blog 比較權威。
PS. 本來是想分章節書寫,誰知道這一套軍體拳打下來收不住了,所以下面基本是以一種很流暢的過程解釋而不是很跳躍,細心看應該會對理解 Handler 機制有所收穫。

Q1: 假如有一個耗時的資料處理,而且資料處理的結果是對 UI 更新影響的,而 Android 中 UI 更新不是執行緒安全的,所以規定只能在主執行緒中更新。

下面我們有兩種選擇:

主執行緒版本:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private Button btnTest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_test);

        init();
    }

    private void init() {
        btnTest = (Button) findViewById(R.id.btn_test);
        btnTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 假裝資料處理
                int i = 0;
                for (i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                // 假裝更新 UI
                Log.d(TAG, "Handle it!" + i);
            }
        });
    }
}複製程式碼

直接在主執行緒中處理資料,接著直接根據處理結果更新 UI。我想弊端大家都看到了,小則 UI 卡頓,大則造成 ANR

子執行緒版本:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private Button btnTest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_test);

        init();
    }

    private void init() {
        btnTest = (Button) findViewById(R.id.btn_test);
        btnTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 假裝資料處理
                        int i;
                        for (i = 0; i < 10; i++) {
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        // 返回處理結果
                        handler.sendEmptyMessage(i);
                    }
                }).start();
            }
        });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // 假裝更新 UI
            Log.d(TAG, "Handle MSG = " + msg.what);
        }
    };
}複製程式碼

這是一種典型的處理方式,開一個子執行緒處理資料,通過 Android 中提供的 Handler 機制進行跨執行緒通訊,把處理結果返回給主執行緒,進而更新 UI。這裡我們就是探討 Handler 是如何把資料傳送過去的。

到這裡,我們瞭解到的就是一個 Handler 的黑盒機制,子執行緒傳送,主執行緒接收。接下來,我們不介紹什麼 ThreadLocalLooperMessageQueue。而是直接從上面的程式碼引出它們的存在,從原理了解它們存在的必要性,然後在談它們內部存在的細節。

一切罪惡源於 handler.sendEmptyMessage();,最終找到以下函式 sendMessageAtTime(Message msg, long uptimeMillis)

Handler.class
/**
 * Enqueue a message into the message queue after all pending messages
 * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
 * Time spent in deep sleep will add an additional delay to execution.
 * You will receive it in {@link #handleMessage}, in the thread attached
 * to this handler.
 * 
 * @param uptimeMillis The absolute time at which the message should be
 *         delivered, using the
 *         {@link android.os.SystemClock#uptimeMillis} time-base.
 *         
 * @return Returns true if the message was successfully placed in to the 
 *         message queue.  Returns false on failure, usually because the
 *         looper processing the message queue is exiting.  Note that a
 *         result of true does not mean the message will be processed -- if
 *         the looper is quit before the delivery time of the message
 *         occurs then the message will be dropped.
 */
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);
}複製程式碼

MessageQueue 出來了,我們避免不了了。裡面主要是 Message next()enqueueMessage(Message msg, long when) 方法值得研究,但是現在還不是時候。

MessageQueue queue = mQueue; 中可以看出我們的 handler 物件裡面包含一個 mQueue 物件。至於裡面存的什麼怎麼初始化的現在也不用太關心。大概有個概念就是這是個訊息佇列,存的是訊息就行,具體實現細節後面會慢慢水落石出。
後面的程式碼就是說如果 queue 為空則列印 log 返回 false;否則執行 enqueueMessage(queue, msg, uptimeMillis); 入隊。那就好理解了,handler 傳送資訊其實是直接把資訊封裝進一個訊息佇列。

Handler.class
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}複製程式碼

這裡涉及 Message,先說下這個類的三個成員變數:

/*package*/ Handler target;

/*package*/ Runnable callback;

/*package*/ Message next;複製程式碼

所以 msg.target = this; 把當前 handler 傳給了 msg。

中間的 if 程式碼先忽略,先走主線:執行了 MessageQueueenqueueMessage(msg, uptimeMillis);方法。接著看原始碼

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

程式碼有點長,不影響主線的小細節就不介紹了,那些也很容易看懂的,但是原理還是值得分析。
if (mQuitting)...,直接看看原始碼初始化賦值的函式是在 void quit(boolean safe) 函式裡面,這裡猜測可能是退出訊息輪訓,訊息輪訓的退出方式也是值得深究,不過這裡不影響主線就不看了。 msg.markInUse(); msg.when = when; 標記訊息在用而且繼續填充 msg,下面就是看註釋了。我們前面介紹的 Message 成員變數 next 就起作用了,把 msg 鏈在一起了。所以這裡的核心就是把 msg 以一種連結串列形式插進去。似乎這一波分析結束了,在這裡劃張圖總結下:


推薦自己根據所觀察到的變數賦值進行繪製圖畫,這樣印象更加深刻。

OK,訊息是存進去了,而且也是在 handler 所在的執行緒中。那麼到底怎麼取出資訊呢?也就是前面小例子

Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        // 假裝更新 UI
        Log.d(TAG, "Handle MSG = " + msg.what);
    }
};複製程式碼

handleMessage() 什麼時候呼叫?這裡基本斷了線索。但是如果你之前哪怕看過類似的一篇文章應該都知道其實在 Android 啟動時 main 函式就做了一些操作。這些操作是必要的,這也就是為什麼我們不能直接在子執行緒中 new Handler();

public static void main(String[] args) {
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
    SamplingProfilerIntegration.start();

    // CloseGuard defaults to true and can be quite spammy.  We
    // disable it here, but selectively enable it later (via
    // StrictMode) on debug builds, but using DropBox, not logs.
    CloseGuard.setEnabled(false);

    Environment.initForCurrentUser();

    // Set the reporter for event logging in libcore
    EventLogger.setReporter(new EventLoggingReporter());

    // Make sure TrustedCertificateStore looks in the right place for CA certificates
    final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
    TrustedCertificateStore.setDefaultUserDirectory(configDir);

    Process.setArgV0("<pre-initialized>");

    Looper.prepareMainLooper(); // -------1

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

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

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

    // End of event ActivityThreadMain.
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    Looper.loop(); // -------3

    throw new RuntimeException("Main thread loop unexpectedly exited");
}複製程式碼

可以看出這裡在獲取 sMainThreadHandler 之前進行了 Looper.prepareMainLooper(); 操作,之後進行了 Looper.loop(); 操作。

下面開始分析:

Loopr.class
 /** Initialize the current thread as a looper.
  * This gives you a chance to create handlers that then reference
  * this looper, before actually starting the loop. Be sure to call
  * {@link #loop()} after calling this method, and end it by calling
  * {@link #quit()}.
  */
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's 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 的時候用,第三個是主執行緒自己用的。由於這裡訊息傳遞以主執行緒為線索。prepare(false);說明了這是主執行緒,在 sThreadLocal.set(new Looper(quitAllowed)); 中的 quitAllowed 為 false 則說明主執行緒的 MessageQueue 輪訓不能 quit。這句程式碼裡還有 ThreadLocal 的 set() 方法。先不深究實現,容易暈,這裡需要知道的就是把一個 Looper 物件“放進”了 ThreadLocal,換句話說,通過 ThreadLocal 可以獲取不同的 Looper。
最後的 sThreadLocal.get(); 展示了 get 方法。說明到這時 Looper 已經存在啦。
現在看看 Looper 類的成員變數吧!

Looper.class
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper;  // guarded by Looper.class

final MessageQueue mQueue;
final Thread mThread;複製程式碼

在這裡先介紹一下 ThreadLocal 的上帝視角吧。直接原始碼,可以猜測這是通過一個 ThreadLocalMap 的內部類對執行緒進行一種 map。傳進來的泛型 T 正是我們的 looper。所以 ThreadLocal 可以根據當前執行緒查詢該執行緒的 Looper,具體怎麼查詢推薦看原始碼,這裡就不介紹了。

/**
 * Returns the value in the current thread's copy of this
 * thread-local variable.  If the variable has no value for the
 * current thread, it is first initialized to the value returned
 * by an invocation of the {@link #initialValue} method.
 *
 * @return the current thread's value of this thread-local
 */
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();
}

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

分析到這裡,handler 和 looper 都有了,但是訊息還是沒有取出來?
這是看第三句 Looper.loop();

Looper.class
/**
 * 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
        final Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

        final long traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        try {
            msg.target.dispatchMessage(msg);
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }

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

一開始也是獲取 Looper,但是那麼多 Looper 怎麼知道這是哪個 Looper 呢?這先放著待會馬上解釋。把 loop() 函式主要功能搞懂再說。
接下來就是獲取 Looper 中的 MessageQueue了,等等,這裡提出一個疑問,前面說了 Handler 中也存在 MessageQueue,那這之間存在什麼關係嗎?(最後你會發現其實是同一個)
先往下看,一個死迴圈,也就是輪訓訊息嘍,中間有一句 msg.target.dispatchMessage(msg); 而前面介紹 msg.target 是 handler 型引數。所以和 handler 聯絡上了。

Handler.class
/**
 * 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() 方法。

Step 1:Looper.prepare();

在 Looper 中有一個靜態變數 sThreadLocal,把建立的 looper “存在” 裡面,建立 looper 的同時建立 MessageQueue,並且和當前執行緒掛鉤。

Step 2:new Handler();

通過上帝 ThreadLocal,並根據當前執行緒,可獲取 looper,進而獲取 MessageQueue,Callback之類的。
```java
Handler.class
/**

  • Use the {@link Looper} for the current thread with the specified callback interface
  • and set whether the handler should be asynchronous.
    *
  • Handlers are synchronous by default unless this constructor is used to make
  • one that is strictly asynchronous.
    *
  • Asynchronous messages represent interrupts or events that do not require global ordering
  • with respect to synchronous messages. Asynchronous messages are not subject to
  • the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
    *
  • @param callback The callback interface in which to handle messages, or null.
  • @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
  • each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
    *
  • @hide
    */
    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 that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue; // 前面的兩個 MessageQueue 聯絡起來了,疑問已解答。
mCallback = callback;
mAsynchronous = async;複製程式碼

}
`` 這個函式可以說明在 new Handler() 之前該執行緒必需有 looper,所以要在這之前呼叫Looper.prepare();`。

Step 3:Looper.loop();

進行訊息迴圈。

基本到這裡整個過程應該是清楚了,這裡我畫下我的理解。

那麼我們現在來看一下 handler 是怎麼準確傳送資訊和處理資訊的。注意在 handler 傳送資訊之前,1、2、3 步已經完成。所以該獲取的執行緒已經獲取,直接往該執行緒所在的 MessageQueue 裡面塞資訊就行了,反正該資訊會在該 handler 所線上程的 looper 中迴圈,最終會通過訊息的 target 引數呼叫 dispatchMessage(),而在 dispatchMessage() 中會呼叫我們重寫的 handleMessage() 函式。

多謝閱讀

相關文章