HandlerThread的使用场景和用法详解
public class MyHandlerThread extends HandlerThread {
private Handler handler;
public MyHandlerThread(String name) {
super(name);
}
@Override
protected void onLooperPrepared() {
super.onLooperPrepared();
// 在HandlerThread的Looper准备好后创建Handler
handler = new Handler(getLooper()) {
@Override
public void handleMessage(Message msg) {
// 在这里处理消息
// 可以执行耗时操作,然后将结果发送到UI线程
}
};
}
public void sendMessageToBackgroundThread() {
if (handler != null) {
// 发送消息到后台线程
handler.sendMessage(handler.obtainMessage());
}
}
}