1. 什么是HandlerThread?
A Thread that has a Looper. The Looper can then be used to create Handlers.
Note that just like with a regular Thread, start() must still be called.
handlerThread本质上是一个线程类,继承了Thread;
他就是在一个子线程内部创建并管理一个Looper;
2. 为什么使用HandlerThread?
自带Looper消息循环;可以快速创建一个带有Looper的线程,更加方便、便捷;
3. 怎么使用HanderThread?
注:创建HandlerThread后必须先调用start()方法,其会先调用run()方法,创建Looper对象;
Button handlerThreadBt = findViewById(R.id.main_handler_thread_bt);
Context context = getApplicationContext();
Thread thread = new Thread(() -> {
// 1、创建HandlerThread对象
HandlerThread handlerThread = new HandlerThread("myToast");
// 2、必须先开启HandlerThread线程
handlerThread.start();
// 3、构建子线程Handler
Handler handler = new Handler(handlerThread.getLooper(), msg -> {
if (msg.what == 1) {
Toast toast = Toast.makeText(context, getText(R.string.handler_thread_toast), Toast.LENGTH_LONG);
toast.show();
return true;
}
return false;
});
// 4、在子线程发送消息,更新UI
handlerThreadBt.setOnClickListener(v -> {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
});
});
thread.start();