Handler Thread

Introduction
First of all, let's take a look at why we use HandlerThread? In order to achieve multiple tasks at the same time in our application, we will create multiple threads in the application. In order to facilitate communication between multiple threads, we will use Handler to implement communication between threads.

Let's see how to instantiate a Handler in a thread. To instantiate Handler in a thread, we need to ensure that Looper is included in the thread (Note: UI-Thread includes Looper by default).

The method of creating a Looper for a thread is as follows: first call Looper.prepare() in the thread run() method to initialize the Looper, then the run() method finally calls Looper.loop(), so that we create the Looper in the thread. (Note: Looper.loop() method is an infinite loop by default)

Is there a simpler way for us to implement Looper? Of course, this is our HandlerThread. Let's take a look at Android's description of HandlerThread:

Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.

Use steps
though the documentation of HandlerThread compares Simple, but it's not as easy to use as you might think.

Creating a HandlerThread creates a thread that contains Looper.

HandlerThread handlerThread = new HandlerThread("leochin.com");
handlerThread.start(); //After creating HandlerThread, you must remember to start()
to get HandlerThread's Looper

Looper = handlerThread.getLooper();
Create Handler and initialize Handler through Looper

handler = new Handler(looper);
Through the above three steps, we HandlerThread is successfully created. Sending a message through the handler will be executed in the child thread.

If you want HandlerThread to exit, you need to call handlerThread.quit();.

Of course, HandlerThread can also be implemented in the form of ordinary threads, that is, the Looper thread

calls the Looper.prepare() and Looper.loop() methods in the thread

class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          [b]Looper.prepare();[/b]

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          [b]Looper.loop();[/b]
      }
  }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326942514&siteId=291194637