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

從源碼看 Android Handler 機制:線程通訊的背後原理

編輯:關於 Android 程式設計

先看一段大家都很熟悉的程式碼:

Thread thread = new Thread() {
    public void run() {
        // 子線程中發送消息給主線程
        Message msg = new Message();
        msg.what = 200;
        msg.obj = param;
        msg.arg1 = 3;
        handler.sendMessage(msg);
    }
};

Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        // 主線程接收到消息,更新 UI
    }
};

在 Android 中有兩種線程:主線程(UI 線程,不允許做耗時操作)與子線程(非 UI 線程,不允許操作介面元素)。Handler 就是實現兩者溝通的橋梁。但它究竟是怎麼做到的?我們到源碼裡找答案。

Handler 的構造函數

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

public Handler(Callback callback, boolean async) {
    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

構造方法中初始化了兩個變量:

final MessageQueue mQueue;   // 消息隊列(鏈表結構)
final Looper mLooper;        // 消息處理器

其中 MessageQueue 是 Looper 的成員屬性。

sendMessage 的落點

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    MessageQueue queue = mQueue;
    if (queue == null) {
        return false;
    }
    return enqueueMessage(queue, msg, uptimeMillis);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    // 注意這一行:把 Handler 自己賦值給 Message 的 target 屬性,後面會用到
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

MessageQueue 的鏈表插入邏輯

boolean enqueueMessage(Message msg, long when) {
    synchronized (this) {
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
            // 成為新的表頭,若有阻塞則喚醒事件隊列
            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;
        }
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}

由此可得知:消息在 MessageQueue 中以鏈表方式存儲,類別裡以成員變量 mMessages 記錄排在最前面的那則消息。每有新消息插入,就依時間(when)先後重新排列,時間最早的在最前面。

Looper 的標準用法

在 Looper 類別的註解中,官方給了這樣的範例:

class LooperThread extends Thread {
    public Handler mHandler;

    public void run() {
        Looper.prepare();
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // process incoming messages here
            }
        };
        Looper.loop();
    }
}

這個範例可以直接套用在日常開發中。注意它在建立 Handler 的前後分別呼叫了兩個靜態方法:

Looper.prepare();
Looper.loop();

我們知道 Activity 運行在 UI 線程中,而 UI 線程也是一條線程,因此大膽猜測:UI 線程載入 Activity 的前後,應該也呼叫了這兩個方法。

prepare:為當前線程準備 Looper

public static void prepare() {
    prepare(true);
}

// 設置當前線程私有的 Looper 對象
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));
}

// 定義當前線程私有的 Looper 對象
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

// 獲取當前線程私有的 Looper 對象
public static Looper myLooper() {
    return sThreadLocal.get();
}

prepare() 實際上是為當前線程建立自己私有的 Looper 對象,連同它的屬性 MessageQueue 也是當前線程獨有的。其他線程可以有自己的 Looper,但不能存取當前線程的 Looper。這也正是為什麼 Handler 若在不支援 Looper 的線程中建立,會直接丟出例外。

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;
    for (;;) {
        Message msg = queue.next();   // might block
        if (msg == null) {
            // 沒有消息代表隊列即將退出
            return;
        }
        msg.target.dispatchMessage(msg);
        msg.recycle();
    }
}

這裡用一個無限迴圈不斷從 MessageQueue 取出消息,然後呼叫消息的 target 去分發它。Target 是什麼?正是前面 enqueueMessage() 中所設定的 Handler 自己。

dispatchMessage:回到 handleMessage

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

終於又見到我們最熟悉的 handleMessage(msg) 了。這裡也說明了 Callback 的優先順序:訊息若有 runnable callback 會優先執行,其次才是 Handler 的 mCallback,最後才落到子類別覆寫的 handleMessage。

總結

在多線程環境中,主線程與子線程的交互依靠一個鏈表結構的消息隊列(MessageQueue):子線程只管往裡頭放消息(Message),消息按時間先後排列;主線程則用一個消息處理器(Looper)不斷地把它們逐一取出並分發處理。

原文作者:容新華技術博客

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