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

[Android] 深入解析 Handler 的消息機制

編輯:關於 Android 程式設計

在一次面試中,技術面試官問到了 Handler 的消息機制。細細回想,日常開發中最常見的用法,就是在主線程(Activity)建立一個 Handler 物件,另開一個 Thread 非同步載入資料,載入完成後再把結果 send 回主線程的 Handler,由它來處理並更新界面。本文就從這個熟悉的場景出發,深入剖析其底層原理。

基礎用法範例

public class HandlerTestActivity extends Activity {
    private TextView tv;
    private static final int UPDATE = 0;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // 接收消息並更新 UI 線程上的控制項
            if (msg.what == UPDATE) {
                tv.setText(String.valueOf(msg.obj));
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.tv);

        new Thread() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 100; i++) {
                        Thread.sleep(500);
                        Message msg = new Message();
                        msg.what = UPDATE;
                        msg.obj = "更新後的值:" + i;
                        handler.sendMessage(msg);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

Looper、MessageQueue 與 Handler 的關係

每個 Thread 都對應一個 Looper,這個 Looper 類用於管理其中的消息隊列(MessageQueue)。而 Handler 的作用,則是把消息傳遞到這個隊列中,並在 Looper 取出消息後交給對應的 Handler 處理。

Looper 是與線程綁定的。若想在子線程中取得一個 Looper,需要這樣做:

Looper.prepare();
Looper looper = Looper.myLooper();

Looper 源碼解析

// 準備 Looper 相關事宜
public static void prepare() {
    // 每個線程只能有一個 Looper 物件
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper());
}

// 構造函數:新建消息隊列,並記錄當前線程
private Looper() {
    mQueue = new MessageQueue();
    mRun = true;
    mThread = Thread.currentThread();
}

// 從當前線程的 ThreadLocal 中取出設置的 Looper
public static final Looper myLooper() {
    return (Looper) sThreadLocal.get();
}

// 運行消息隊列,需搭配 quit() 才能結束循環
public static void loop() {
    Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    MessageQueue queue = me.mQueue;
    while (true) {
        Message msg = queue.next(); // 可能阻塞
        if (msg != null) {
            if (msg.target == null) {
                // target 為空是退出消息的標識
                return;
            }
            msg.target.dispatchMessage(msg);
            msg.recycle();
        }
    }
}

Handler 源碼解析

public Handler() {
    // 先取得一個 Looper 物件;若在子線程,需先 prepare()
    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 = null;
}

// 從全域消息池取得一個 Message,比 new 更有效率
public final Message obtainMessage() {
    return Message.obtain(this);
}

在子線程中實作消息傳遞

new Thread() {
    public void run() {
        Looper.prepare();
        Handler h = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg != null) {
                    String strMsg = (String) msg.obj;
                    System.out.println(strMsg);
                }
            }
        };
        Message msg = h.obtainMessage();
        msg.obj = "add";
        msg.sendToTarget();
        Looper.loop(); // 進入循環,查看消息隊列
    }
}.start();

關鍵重點

1. 子線程也可以有 Handler。Handler 本質上只是從當前線程取得 Looper,用以監聽與操作 MessageQueue。
2. 子線程必須先呼叫 prepare() 才能取得 Looper。因為子線程只是一個普通線程,其 ThreadLocal 中並未設置過 Looper,若直接建立 Handler 便會抛出異常;而 Looper 的 prepare() 方法中的 sThreadLocal.set(new Looper()) 正是完成 Looper 設置的關鍵。

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