HandlerThreads 和 Threads 之間的通訊

由於 Handlers 用於將 Messages 和 Runnables 傳送到 Thread 的訊息佇列,因此很容易在多個執行緒之間實現基於事件的通訊。具有 Looper 的每個執行緒都能夠接收和處理訊息。HandlerThread 是一個實現這樣一個 Looper 的 Thread,例如主執行緒(UI Thread)實現了 HandlerThread 的功能。

為當前執行緒建立處理程式

Handler handler = new Handler();

為主執行緒建立處理程式(UI 執行緒)

Handler handler = new Handler(Looper.getMainLooper());

將 Runnable 從另一個執行緒傳送到主執行緒

new Thread(new Runnable() {
    public void run() {
        // this is executed on another Thread

        // create a Handler associated with the main Thread
        Handler handler = new Handler(Looper.getMainLooper());

        // post a Runnable to the main Thread
        handler.post(new Runnable() {
            public void run() {
                // this is executed on the main Thread
            }
        });
    }
}).start();

為另一個 HandlerThread 建立一個 Handler 並向其傳送事件

// create another Thread
HandlerThread otherThread = new HandlerThread("name");

// create a Handler associated with the other Thread
Handler handler = new Handler(otherThread.getLooper());

// post an event to the other Thread
handler.post(new Runnable() {
    public void run() {
        // this is executed on the other Thread
    }
});