Android Asynchronous Journey: Exploring HandlerThread

Preface

When we need to perform some time-consuming tasks in Android applications, such as network requests, database operations, or other operations that need to be performed in background threads, we usually use asynchronous tasks to complete these tasks. In Android, there are many ways to implement asynchronous operations, one of which is to use HandlerThread.

In this blog, we will explore HandlerThread, understand how it works and how to use it in Android applications to perform asynchronous operations.

1.Introduction to HandlerThread


     HandlerThread is a class in Android. It inherits from the Thread class and contains a Looper and a Handler internally. This makes it convenient to perform tasks in a background thread and communicate with the UI thread through a Handler. (Handler+Thread)

2.How HandlerThread works


The working principle of HandlerThread is based on the mechanism of threads and message loops. When we create a HandlerThread instance and start it, it will create a new thread in the background and create a Looper in this thread. This Looper will continue to process messages in the message queue until the quit() method is called to stop the loop.

We can obtain this Looper through the getLooper() method of HandlerThread, and then use it to create a Handler. This Handler can be used to send messages to HandlerThread to perform tasks, and can also be used to communicate with the UI thread.

When we send a message to HandlerThread, the message will be added to the HandlerThread's message queue, and then the Looper loop will process these messages and perform the corresponding tasks in the Handler's handleMessage() method.

In general, HandlerThread implements the function of executing tasks in the background thread and communicating with the UI thread through the mechanism of threads and message loops.

3. Why use HandlerThread?


Compared with other asynchronous operation methods, using HandlerThread has the following advantages:

1. Running the loop in a sub-thread reduces the pressure on the main thread and makes the main thread smoother.

2. Serial execution, starting a thread to play the role of multiple threads

3. It has its own message queue and will not interfere with the UI thread.

shortcoming:

1. Since each task queue is executed step by step, once the queue takes too long, the message will be delayed.

2. For operations such as IO, threads wait and cannot be concurrent.

4. How to use HandlerThread?


First, we need to create an instance of HandlerThread and start it. Then, we can obtain the Looper through the getLooper() method of HandlerThread, and then use this Looper to create a Handler. In this way, we can use Handler in HandlerThread to send messages and perform tasks.

Here is a simple example code:

public class MainActivity2 extends AppCompatActivity {
    private HandlerThread handlerThread;
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        // 创建并启动HandlerThread
        handlerThread = new HandlerThread("MyHandlerThread");
        handlerThread.start();
        // 获取HandlerThread的Looper并创建Handler
        handler = new Handler(handlerThread.getLooper()) {
            //设置消息处理
            @Override
            public void handleMessage(@NonNull Message msg) {
                //super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        // 通过主线程Handler.post方法进行在主线程的UI更新操作
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                               Log.e("xxx","成功");
                            }
                        });
                        break;
                }
            }
        };
        send();
    }
    void send(){
        Message msg = Message.obtain();
        msg.what = 1; //消息的标识
        msg.obj = "A"; // 消息的存放
        // b. 通过Handler发送消息到其绑定的消息队列
        handler.sendMessage(msg);
    }
    // 在Activity销毁时结束HandlerThread
    @Override
    protected void onDestroy() {
        super.onDestroy();
        handlerThread.quit();
    }
  }

Guess you like

Origin blog.csdn.net/weixin_63357306/article/details/134559098