The Looper class in Android

Introduction

        The looper class in android is a class used to encapsulate message loops and message queues for message processing in Android threads. Handler can be regarded as a tool class for inserting messages into the message queue.


The role of the looper class

  1. The looper class is used to open a message loop for a thread;

  2. Usually, it interacts with the looper through the handler object. The handler can be regarded as an interface of the looper, which is used to send messages to the specified looper and define the processing method;

  3. In the non-main thread, direct new handler() will report an error, because the looper object is not created by default in the non-main thread, you need to call looper.prepare() to enable the looper;

  4. looper.loop() lets Looper start working, fetches messages from the message queue, and processes messages;

  5. Based on the above knowledge, the main thread can send messages to sub-threads (non-sub-threads), such as the following code.

class LooperThread extends Thread {
      public Handler mHandler;
  
      public void run() {
          Looper.prepare();//启动looper
  
          mHandler = new Handler(Looper.myLooper()) {
              public void handleMessage(Message msg){//处理传入的信息
                  // process incoming messages here
              }
          };
  
          Looper.loop();//处理在这个线程的MQ
      }
  }

 If there is any mistake, I hope all the big guys who are watching can point it out~

Guess you like

Origin blog.csdn.net/weixin_44715733/article/details/127498814