Explanation and examples of using HandlerThread
HandlerThread is a thread class with a Looper, extending from the Thread class and implementing the Runnable interface. Its main purpose is to make it easier to execute a series of tasks in the background thread, and communicate with the main thread through a Handler.
The principle of HandlerThread is as follows:
- Create a Looper object within the HandlerThread and initialize it using the Looper.prepare() method.
- Call the Looper.loop() method to start the message loop mechanism of Looper, allowing the HandlerThread to process messages.
- Create a Handler object within the HandlerThread, which is bound together with the HandlerThread and can process messages within the HandlerThread.
The use of examples is as follows:
public class MyHandlerThread extends HandlerThread {
private Handler mHandler;
public MyHandlerThread(String name) {
super(name);
}
@Override
protected void onLooperPrepared() {
super.onLooperPrepared();
mHandler = new Handler(getLooper()) {
@Override
public void handleMessage(Message msg) {
// 在HandlerThread中处理消息
// ...
}
};
}
public void sendMessage(int what) {
if (mHandler != null) {
mHandler.sendEmptyMessage(what);
}
}
}
Utilize MyHandlerThread in the main thread.
MyHandlerThread handlerThread = new MyHandlerThread("MyHandlerThread");
handlerThread.start();
// 发送消息到HandlerThread中处理
handlerThread.sendMessage(1);
In MyHandlerThread, we override the onLooperPrepared() method to initialize a Handler object and bind it with the HandlerThread. This allows us to call sendMessage() externally to send messages to the HandlerThread for processing.