Handler 機制再瞭解

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

Q1: 假若有一個耗時的數據處理,並且數據處理的結果是對 UI 更新影響的,而 Android 中 UI 更新不是線程安全的,因此規定只能在主線程中更新。android

下面咱們有兩種選擇:安全

主線程版本:

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 卡頓,大則形成 ANRbash

子線程版本:

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。而是直接從上面的代碼引出它們的存在,從原理了解它們存在的必要性,而後在談它們內部存在的細節。app

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

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) 方法值得研究,可是如今還不是時候。async

MessageQueue queue = mQueue; 中能夠看出咱們的 handler 對象裏面包含一個 mQueue 對象。至於裏面存的什麼怎麼初始化的如今也不用太關心。大概有個概念就是這是個消息隊列,存的是消息就行,具體實現細節後面會慢慢水落石出。
後面的代碼就是說若是 queue 爲空則打印 log 返回 false;不然執行 enqueueMessage(queue, msg, uptimeMillis); 入隊。那就好理解了,handler 發送信息實際上是直接把信息封裝進一個消息隊列。ide

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 發送信息以前,一、二、3 步已經完成。因此該獲取的線程已經獲取,直接往該線程所在的 MessageQueue 裏面塞信息就好了,反正該信息會在該 handler 所在線程的 looper 中循環,最終會經過消息的 target 參數調用 dispatchMessage(),而在 dispatchMessage() 中會調用咱們重寫的 handleMessage() 函數。

多謝閱讀

相關文章
相關標籤/搜索