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