Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

從源碼角度剖析 Android Handler 消息機制

編輯:關於 Android 程式設計

在 Android 中做耗時操作後更新 UI,用得最多的就是 Handler:子線程負責網絡訪問、文件讀寫等重活,然後把消息發送回主線程,由主線程完成界面刷新。

用法大家都熟,但原理未必都清楚。本文就從源碼出發,把 Handler 機制完整走一遍。

Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        // 在這裡處理消息
    }
};

先看看官方 API 文檔的說法:

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it.

翻譯過來就是:Handler 能夠通過所關聯線程的 MessageQueue 來發送和處理 Message 與 Runnable 對象。每個 Handler 實例都關聯一個線程以及該線程的消息隊列;創建 Handler 時,它就綁定到了「創建它的那個線程」的消息隊列上。

Handler 有兩大用途:一是把消息或 Runnable 安排到未來某個時刻執行;二是把一個操作提交到另一個線程去完成。

Handler 的構造方法

從構造函數入手,看看實例化時究竟做了什麼。

public Handler() {
    this(null, false);
}

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();      // 關鍵:獲取當前線程的 Looper
    if (mLooper == null) {
        throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;          // 消息隊列來自 Looper
    mCallback = callback;
    mAsynchronous = async;
}

最值得盯住的是這一行:mLooper = Looper.myLooper();。Looper 是什麼?接着往下追。

public static Looper myLooper() {
    return sThreadLocal.get();
}

又冒出一個新東西:ThreadLocal。

ThreadLocal 即「線程局部變量」,它被設計出來正是為了避免線程間共享變量——每個線程都能拿到屬於自己的一份獨立實例。它最核心的就兩個方法:

/** 返回當前線程中該線程局部變量的副本值 */
public T get();

/** 設置當前線程中該線程局部變量的值 */
public void set(T value);

這裡只做點到為止的介紹,有興趣的同學可以另外深入研究。

sThreadLocal 是 Looper 的靜態成員,一般在類加載時就完成了創建。再看 prepare():

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    // 創建 Looper 並保存到 sThreadLocal 中
    sThreadLocal.set(new Looper(quitAllowed));
}

看到這裡,細心的你可能會產生一個疑問:既然 myLooper() 是從 ThreadLocal 裡取 Looper,那如果 prepare() 沒有先被調用過,豈不是必然取不到?可我們平時寫 Handler,壓根就沒調過 Looper.prepare() 啊。

答案在 ActivityThread 的 main() 方法裡——主線程早就替我們調好了。

public static void main(String[] args) {
    // ① 主線程調用 prepareMainLooper() 創建 Looper
    Looper.prepareMainLooper();

    ActivityThread thread = new ActivityThread();
    thread.attach(false);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    AsyncTask.init();

    // ② 進入消息循環
    Looper.loop();

    throw new RuntimeException("Main thread loop unexpectedly exited");
}

ActivityThread.main() 其實就是每一個 Android 應用進程的入口。每啟動一個應用進程,系統都會創建一個 ActivityThread 實例與之對應,這就是我們所說的 UI 線程(主線程)。主線程通過 prepareMainLooper()(內部轉調 Looper.prepare())建立好消息隊列,再通過 loop() 進入循環。

反過來說:如果我們在自己的子線程裡使用 Handler,就必須手動調用 Looper.prepare() 和 Looper.loop()。

loop():消息循環的心臟

public static void loop() {
    final Looper me = myLooper();
    final MessageQueue queue = me.mQueue;

    for (;;) {                            // ① 死循環,不停從隊列取消息
        Message msg = queue.next();       // 沒有消息時會阻塞在這裡
        if (msg == null) {
            // 收到 null 表示隊列即將退出
            return;
        }
        msg.target.dispatchMessage(msg);  // ② 分發消息
        msg.recycle();
    }
}

為保持簡潔,這裡省略了部分代碼,只盯住兩處。

① 處是一個死循環,同時引入了新角色 MessageQueue——顧名思義,它用於存放消息列表,數據結構就是一個隊列。next() 會取出當前該被處理的消息,若暫無可處理消息則阻塞等待。

② 處中,msg.target 究竟是什麼?看 Message 的定義:

/*package*/ Handler target;

原來 target 就是一個 Handler。也就是說,取到消息後,是由「發送這條消息的那個 Handler」來負責分發處理。

那 target 是什麼時候被塞進去的?兩種常見寫法:

  1. new Message():構造函數本身什麼都不做,關鍵在 sendMessage()。它最終會走到 enqueueMessage(),在那裡把 target 設為 this。
  2. Handler.obtainMessage():內部調用 Message.obtain(this),同樣把 target 置為當前 Handler。

Handler 發送消息的流程

public final boolean sendMessage(Message msg) {
    return sendMessageDelayed(msg, 0);
}

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    MessageQueue queue = mQueue;
    if (queue == null) {
        Log.w("Looper", this + " sendMessageAtTime() called with no mQueue");
        return false;
    }
    return enqueueMessage(queue, msg, uptimeMillis);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;              // 把 target 設為自己
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

public final Message obtainMessage() {
    return Message.obtain(this);
}

public static Message obtain(Handler h) {
    Message m = obtain();
    m.target = h;
    return m;
}

可見無論走哪條路,消息入隊時 target 都會被正確設置。接下來看 MessageQueue.enqueueMessage():

boolean enqueueMessage(Message msg, long when) {
    msg.when = when;
    Message p = mMessages;
    boolean needWake;

    if (p == null || when == 0 || when < p.when) {
        // ① 當前消息需要立即處理,needWake 置 true
        msg.next = p;
        mMessages = msg;
        needWake = mBlocked;
    } else {
        // ② 當前消息排在其他消息之後,通常不需要喚醒
        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;
        prev.next = msg;
    }

    // ③ 根據 needWake 決定是否喚醒主線程
    if (needWake) {
        nativeWake(mPtr);
    }
    return true;
}

這裡關注三處:依據新消息的觸發時間與隊首消息的時間做比較,判斷它是該立刻執行,還是排到後面去。① 需要立即處理,喚醒標誌置 true;② 排隊等待,喚醒標誌置 false;③ 最終由 needWake 決定是否調用 nativeWake() 喚醒阻塞中的主線程。

nativeWake() 是一個 native 方法,通過 JNI 實現。Handler 機制底層用的是 Linux 的一種進程間通信方式——管道(Pipe)。管道使用特殊文件,持有兩個文件描述符,一個用於讀、一個用於寫。有興趣的同學可以自己去翻翻相關資料。

消息如何抵達 handleMessage()

在 Looper.loop() 中,若暫無消息處理,主線程便阻塞在 queue.next();一旦被其他線程喚醒,循環繼續,於是執行到 msg.target.dispatchMessage(msg):

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
        return;
    }
    if (mCallback != null) {
        if (mCallback.handleMessage(msg)) {
            return;
        }
    }
    handleMessage(msg);
}

public void handleMessage(Message msg) {
}

dispatchMessage() 依次嘗試三條路徑:先看向 msg.callback(即 Runnable),再看構造時傳入的 Callback 接口,最後才落到 handleMessage()。而 handleMessage() 是個空方法——它留白的地方,正是我們需要重寫並填寫業務邏輯的地方。

至此,Handler 機制從發送到處理的完整閉環就走通了。

最後用兩張圖做個收束,第一張是時序圖,第二張是類調用關係圖,希望能幫大家把整個流程串起來。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved