Handler(三)

126 阅读2分钟

这是我参与11月更文挑战的第11天,活动详情查看:2021最后一次更文挑战

上篇文章介绍了常用的api和内存泄漏的问题,今天我们来简单介绍一下 handlerThread ,并介绍一下它的使用。

handlerThread

handlerThread 继承 thread ,内部比普通线程多了一个 Looper

一个线程有一个 Looper ,一个 MessageQueue 对象,无数个 HandlerThreadLocal 保证每个线程都有自己的 looper ,一直有一个,一个线程可以创建无数个 Handler ,但使用同一个MessageQueue ,也就是一个 Looper

1、handleMessage() 可以做耗时操作,但是不能更新ui

2、如果不手动的调用 HandlerThread.quit() 或者 HandlerThread.quitSafely() 方法,HandlerThread 会将持续的接收新的任务事件。

3、只有 handleMessage() 方法执行完,这轮的任务才算完成, HandlerThread 才会去执行下一个任务。而且在此次执行时,即使手动的去调用 quit() 方法, HandlerThread 的此次任务也不会停止。但是,会停止下轮任务的接收。

4、让HandlerThread 能够中止接收事件的方法一共有以下两种:

(1)quit() ,实际上执行了 MessageQueue 中的 removeAllMessagesLocked 方法,该方法的作用是把 MessageQueue 消息池中所有的消息全部清空,无论是延迟消息(带Delayed的)还是非延迟消息。

(2)quitSafely() ,执行了 MessageQueue 中的 removeAllFutureMessagesLocked 方法,该方法只会清空 MessageQueue 消息池中所有的延迟消息,并将消息池中所有的非延迟消息派发出去让 Handler 去处理,quitSafely相比于quit方法安全之处在于清空消息之前会派发所有的非延迟消息。

HandlerThread使用

public class MainActivity extends AppCompatActivity {

private HandlerThread thread;
static Handler mHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //创建一个HandlerThread
    thread = new HandlerThread("MyHandlerThread");
    thread.start();

    //使用HandlerThread的looper对象创建Handler
    mHandler = new Handler(thread.getLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0x1) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }
    });

    //停止handlerthread接收事件
    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            thread.quit();
        }
    });

    //发送Message
    mHandler.sendEmptyMessage(0x1);
}

}