Principle Analysis | Principle and Use of HandlerThread in Android

Principle Analysis | Principle and Use of HandlerThread in Android

HandlerThread is a thread class used in Android development to start a new thread with a Looper. It contains a Looper and a Handler, which can easily send and process messages. By processing tasks in HandlerThread and sending the results back to the main thread through Handler, data transfer and interaction between threads can be achieved.

Principle Analysis

Create a HandlerThread instance by calling the HandlerThread constructor and passing in a string as the thread name.

 public HandlerThread(String name) { super(name); mPriority = Process.THREAD_PRIORITY_DEFAULT; }

HandlerThread inherits from Thread and is essentially a thread. Its construction method mainly performs some initialization operations.

We know that the HandlerThread class is actually a Thread, and the start() method must call the run method of Thread. Let's take a look at the specific implementation of its run method.

 @Override public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; }

The Looper.prepate() method and the Loop.loop() method are called internally. If you are familiar with the Android asynchronous message mechanism, you will know that in the Android system, there are Looper objects, MessageQueue objects, and Handler objects.

So through the run method, we can know that we created the Looper and MessageQueue of the HandlerThread thread we created.

It should be noted here that before calling the Looper.loop() method, an empty implementation method onLooperPrepared() is called. We can implement our own onLooperPrepared method to do some Looper initialization operations;

In the run method, there is a notifyAll() after the mLooper is created, and a wait() in getLooper(). Because mLooper is executed in a thread, and our Handler is initialized in the UI thread, that is, we must wait until the mLooper is created before we can correctly return to getLooper(). wait()``notify() is to solve the synchronization problem of the two threads.

We need to initialize the Handler instance when using it:

 Handler handler = new Handler(handlerThread.getLooper()) { @Override public void handleMessage(Message msg) { // 处理消息Log.i("HandlerThread", "接收到消息:" + msg.obj.toString()); } };

The HandlerThread's Looper object is passed into the Handler's construction method, so the Handler object has a reference to the Looper object in the HandlerThread thread. Call the Handler's sendMessage method to send a message, and the message can be received in the Handler's handleMessage method.

Basic Usage

  1. Creating a HandlerThread Instance

Create a HandlerThread instance by calling the HandlerThread constructor and passing in a string as the thread name.

 HandlerThread handlerThread = new HandlerThread("mHandlerThread");

"mHandlerThread" is the name of the thread.

  1. Start HandlerThread

After creating a HandlerThread instance, you need to call the start() method to start the thread.

 handlerThread.start();
  1. Get Handler

After the HandlerThread is started, a Handler instance associated with the HandlerThread is obtained by calling the getLooper() method and passing it to the Handler constructor, which is used to send and process messages in the HandlerThread.

 Handler handler = new Handler(handlerThread.getLooper()) { @Override public void handleMessage(Message msg) { // 处理消息Log.i("HandlerThread", "接收到消息:" + msg.obj.toString()); } };
  1. Sending a message to HandlerThread

Send a message to the HandlerThread using the Handler instance created in the previous step.

 // 使用sendMessage()方法发送消息Message message = Message.obtain(); message.obj = "111111"; handler.sendMessage(message); message = Message.obtain(); message.obj = "222222"; handler.sendMessage(message); // 或者使用post()方法发送Runnable对象handler.post(new Runnable() { @Override public void run() { Log.i("HandlerThread", "执行Runnable的run方法"); } });
  1. Processing Messages

Process messages sent from the main thread or other threads in the handleMessage() method of Handler.

  1. Stop HandlerThread

The message loop is stopped by calling the quit() or quitSafely() method of the Handler. The HandlerThread terminates after completing the current message processing.

 handler.quit(); // 或者handler.quitSafely();
  1. Precautions
  • Dispose of any resources associated with the HandlerThread after it stops to avoid potential memory leaks or other problems.
  • The tasks in HandlerThread are executed serially. If a task takes too long to execute, subsequent tasks may be delayed.
  • Pay attention to thread safety issues and ensure that data is properly synchronized and shared between multiple threads.

<<:  Understand how the Android class loader works and the role of DexPathList in the class loading process

>>:  RESTful API Design and .NET Core Implementation

Recommend

7 steps to help you write a clear plan

I believe this phenomenon should be quite common ...

Jupiter and the Moon are coming again! Are you ready? Don’t miss it this time

March 15, 2024: Mercury, bright Jupiter, and the ...

7 ways for physical stores to conduct private domain community marketing!

When doing store customer development activities,...

New gameplay of Douyin Blue V Matrix

1. What is a matrix? The advanced method of accou...

WeChat official data revealed: What kind of articles are more popular

With 468 million monthly active users, WeChat has...

How to prevent fumonisin poisoning in summer?

How to prevent fumonisin poisoning in summer? Zha...

Don’t know how to plan advertising? Here is a complete set of templates!

Information flow advertising is now the new favor...

There is a way to save the dinosaurs! But it's 66 million years too late...

September 27, 2022, Beijing time. For two asteroi...