What is Looper and when do you use it?

Asked 2 years ago, Updated 2 years ago, 34 views

I'm learning how to play Android. I want to know what class Looper is. And how to use it. I read the document about the Android Looper class, but I don't think I fully understand it. I think there are various uses, but I didn't understand the reason for using them. Please explain exactly what Looper is and when you use it.

android android-looper

2022-09-21 20:47

1 Answers

: The message is a signal between threads, so sending it to the handler does not mean that it is processed immediately. Because messages can occur simultaneously, stack them in the Message Queue and process them. Roofer is the one who takes out and processes the contents in the queue one by one. The main thread has a looper and processes the contents of the queue through an infinite loop.

static void prepare()
static void loop()
void quit()

Thread getThread() // Get thread connected to looper.
Static Looper getMainLooper() // Find the main looper of the application
Static Looper my Looper() // got the looper of current thread. Since not all threads have loops, null may be returned.
 Message msg = Message.obtain();
msg.what = 0;
mThread.mBackHandler.sendMessage(msg);

CalcThread mThread = new CalcThread(mHandler);
mThread.setDaemon(true);
mThread.start();

Handler mHandler = new Handler(){
   public void handleMessage(Message msg){
      switch(msg.what) {
      case 0:
         // // To do
      }
   }
}

class CalcThread extends Thread{
   Handler mMainHandler;
   CalcThread(Handler handler){
         mMainHandler = handler;
   }

   public void run(){
      Looper.prepare();
      Looper.loop();
   }

   public Handler mBackHandler = new Handler(){
      public void handleMessage(Message msg){
         Message retmsg = Message.obtain();
         switch(msg.what){
         case 0:
            try{ Thread.sleep(100); } catch (InterruptedException e) { ; }
            retmsg.what = 0;
            retmsg.arg1 = msg.arg1 * msg.arg1;
            retmsg.obj = new Double(Math.sqrt((double)msg.arg1));
         }
         mMainHandler.sendMessage(retmsg);
      }
   }
}


2022-09-21 20:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.