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

Handler 訊息傳遞處理機制深度解析

編輯:關於 Android 程式設計

Android 是訊息驅動的,實現訊息驅動有幾個要素:訊息的表示(Message)、訊息隊列(MessageQueue)、負責循環取出訊息的 Looper,以及負責處理訊息的 Handler。本文從使用方式一路談到源碼層面的運作流程。

1. 學習路線圖


2. Handler 類別的引入


3. Handler 的執行流程圖

名詞解析:

  • UI 線程:即主線程,系統在建立時會初始化一個 Looper,並建立與之關聯的 MessageQueue。
  • Handler:負責發送與處理訊息,欲正常使用,當前線程需有 Looper。
  • Message:Handler 接收與處理的訊息物件。
  • MessageQueue:訊息隊列,先進先出,於初始化 Looper 時建立。
  • Looper:每個線程只能有一個,管理 MessageQueue 並不斷取出 Message 分發給對應的 Handler。

簡單來說:當子線程想修改 Activity 中的 UI 元件時,可建立一個 Handler 向主線程發送訊息;訊息會先進入主線程的 MessageQueue 等待,由 Looper 先入先出取出,再依 what 屬性分發給對應的 Handler 處理。

4. Handler 的相關方法

  • void handleMessage(Message msg):處理訊息的方法,通常被覆寫。
  • sendEmptyMessage(int what):發送空訊息。
  • sendEmptyMessageDelayed(int what, long delayMillis):延時發送空訊息。
  • sendMessage(Message msg):立即發送訊息。
  • sendMessageDelayed(Message msg):延時發送訊息。
  • boolean hasMessage(int what):檢查隊列中是否含指定 what 的訊息。

5. Handler 的使用範例

(1)Handler 寫在主線程

主線程已由系統初始化 Looper,直接建立 Handler 即可發送與處理訊息。以下以 Timer 定時切換圖片形成幀動畫為例:

 public class MainActivity extends Activity {
    int imgids[] = new int[]{ R.drawable.s_1, R.drawable.s_2, R.drawable.s_3, R.drawable.s_4,
            R.drawable.s_5, R.drawable.s_6, R.drawable.s_7, R.drawable.s_8 };
    int imgstart = 0;
    final Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {
                imgchange.setImageResource(imgids[imgstart++ % 8]);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ImageView imgchange = (ImageView) findViewById(R.id.imgchange);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() { myHandler.sendEmptyMessage(0x123); }
        }, 0, 200);
    }
}

(2)Handler 寫在子線程

若 Handler 寫在子線程,需自行建立 Looper,流程為:呼叫 Looper.prepare() 為當前線程建立 Looper(其建構子會建立 MessageQueue)→ 建立 Handler 並覆寫 handleMessage() → 呼叫 Looper.loop() 啟動循環。以下以計算質數為例:

 public class CalPrime extends Activity {
    static final String UPPER_NUM = "upper";
    EditText etNum;
    CalThread calThread;

    class CalThread extends Thread {
        public Handler mHandler;
        public void run() {
            Looper.prepare();
            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 0x123) {
                        int upper = msg.getData().getInt(UPPER_NUM);
                        List nums = new ArrayList();
                        outer: for (int i = 2; i <= upper; i++) {
                            for (int j = 2; j <= Math.sqrt(i); j++) {
                                if (i != 2 && i % j == 0) { continue outer; }
                            }
                            nums.add(i);
                        }
                        Toast.makeText(CalPrime.this, nums.toString(), Toast.LENGTH_LONG).show();
                    }
                }
            };
            Looper.loop();
        }
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        etNum = (EditText) findViewById(R.id.etNum);
        calThread = new CalThread();
        calThread.start();
    }
    public void cal(View source) {
        Message msg = new Message();
        msg.what = 0x123;
        Bundle bundle = new Bundle();
        bundle.putInt(UPPER_NUM, Integer.parseInt(etNum.getText().toString()));
        msg.setData(bundle);
        calThread.mHandler.sendMessage(msg);
    }
}

6. Handler 的工作流程

Android 的訊息機制主要由 Handler、Looper、MessageQueue、Message 組成,Handler 的運行依賴後三者。

Looper

應用啟動時會建立主線程(ActivityThread),其 main 方法是程式入口:

 public static void main(String[] args) {
    ...... Looper.prepareMainLooper();
    ActivityThread thread = new ActivityThread();
    thread.attach(false);
    ...... Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

prepareMainLooper 為主線程建立 Looper,loop 則開啟訊息循環。由於最後會拋出例外,可推知 loop 內必為死循環,也就是主線程的訊息循環不允許退出。Looper 的建構子如下:

 private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

它在其中建立訊息隊列並保存當前線程。由於建構子為 private,無法手動 new,需透過 prepare 方法建立,並將 Looper 存入 ThreadLocal:

 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。ThreadLocal 實現了本地變數儲存,各線程只能取得自己存放的資料。prepareMainLooper 為主線程建立 Looper 並設定不允許退出,可透過 getMainLooper 取得:

 public static void prepare() { prepare(true); }
public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}

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(); // 可能阻塞
        if (msg == null) { return; } // 隊列退出時回傳 null
        msg.target.dispatchMessage(msg);
        msg.recycleUnchecked();
    }
}

正如所料,loop 內確實存在死循環,唯一退出方式是訊息隊列回傳 null。透過 queue.next() 取得訊息後,msg.target 即發送訊息的 Handler,交由 dispatchMessage 處理,完成後回收。也可透過 quit 與 quitSafely 退出循環,其本質是呼叫訊息隊列的 quit 方法:

 public void quit() { mQueue.quit(false); }
public void quitSafely() { mQueue.quit(true); }

MessageQueue

MessageQueue 即訊息隊列,內部以單鏈表實作,以提高插入與刪除效率。

Handler

Handler 的建構子如下:

 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;
}

可見在沒有 Looper 的線程中無法建立 Handler。因此在子線程使用 Handler 前,必須先建立 Looper 並開啟訊息循環。

總結

梳理整個流程:主線程建立時為其建立一個 Looper,Looper 內部同時建立一個 MessageQueue;建立 Handler 時取出當前線程的 Looper,並透過它取得 MessageQueue;Handler 在子線程發送訊息,等同在該隊列中新增一筆 Message;最後由 Looper 的訊息循環取出這筆 Message 並交由 Handler 處理。

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