Create handler and Looper in child threads and interact with the main thread

Source: Internet
Author: User

Analysis of the above article, the basic understanding of the implementation of the principle of handler, by hot iron, here we use the handler principle, in the sub-thread to create a handler and Looper

Maybe a lot of interviews ask, can I get a new handler in the sub-thread?

The answer is yes, but since the main thread system default in Activitythread will help us create good one looper and messagqueue, we don't need to manually create

(manual creation would be an error, since only one looper and MessageQueue are run by default in a thread, see Threadlocal code principle),

While there is no looper in the child thread, we must learn the code in Activitythread to create a looper manually (MessageQueue is not created because it has been created by default in the Looper constructor method)

  1. On the code, the sub-threading class, which maintains a looper
    1.   

      Import Android.os.Handler;
      Import Android.os.Looper;
      Import Android.os.SystemClock;
      /**
      * Sub-threading class where child threads Looper
      * @author Administrator
      *
      */
      public class Mylooperthread extends Thread {
      Private Looper Mlooper;
      int i=5;
      /**
      * Mainactivity in Handler
      */
      Private Handler Mhandler;
      /**
      * Construction method accepts the main thread of the handler convenient to use the main thread of the handler to send messages to the main thread of the Looper
      * @param Mhandler
      */
      Public Mylooperthread (Handler Mhandler) {
      Super ();
      This.mhandler = Mhandler;
      }
      Private Handler looperthreadhandler=new Handler () {
      public void Handlemessage (Android.os.Message msg) {
      Switch (msg.what) {
      Case 1:
      SYSTEM.OUT.PRINTLN ("The main thread of the message came ....");
      Break

      Default
      The mythread thread sends a 0 message, performing a time-consuming operation
      System.out.println ("Start execution time-consuming operation ....");
      Systemclock.sleep (2000);
      Systemclock.sleep (2000);
      if (i>0) {
      i-=2;
      System.out.println ("Time-consuming operation has finished executing the next ....");
      Continuous polling execution
      Looperthreadhandler.sendemptymessage (0);
      }else{
      Operation complete send message to main thread
      Mhandler.sendemptymessage (0);
      System.out.println ("All tasks completed, waiting for ing ....");
      }
      Break
      }

      };
      };

      @Override
      public void Run () {
      Super.run ();
      Initializes a looper by default in its constructor method
      Looper.prepare ();
      Synchronized (this) {
      Mlooper = Looper.mylooper ();
      Notifyall ();
      }
      Looper.loop ();
      SYSTEM.OUT.PRINTLN ("executed");

      }

      Public Looper Getmlooper () {
      return mlooper;
      }
      Public Handler GetHandler () {
      return looperthreadhandler;
      }
      public void SetHandler (Handler Handler) {
      This.looperthreadhandler = handler;
      }

      }

      The above code is a bit long, mainly creating a sub-thread class, and then creating a looper in its run () method and polling, the construction method accepts a main thread of the handler, so that after the time-consuming operation is completed, the use of this handler to send a message to the main thread, here we can find , to send a message to a different thread, you have to get the handler to the corresponding thread, and handler on which thread it was created, it's bound to the current thread.

  2. The second class of thread class is to use this thread to Cheng a message to the Looper line above and to start its time-consuming task
    1.  
      /*** Thread class gets looper concurrent empty message in child thread *@authorMr.wang **/ Public classMyThreadextendsThread {mylooperthread looperthread;  PublicMyThread (Mylooperthread looperthread) {Super();  This. Looperthread =Looperthread; } @Override Public voidrun () {Super. Run (); Looperthread.gethandler (). Sendemptymessage (0); System.out.println ("Executing in a child thread"); }    }

      This code is relatively well understood, the construction method accepts the handler in the Looper thread, in order to send a message to him, and finally send a message in the run () method, start the Looper thread time-consuming task.

  3. Third class, the class where the main thread is Hanler
    1.  
      Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.widget.Toast;/*** Main Thread class *@authorMr.wang*/ Public classMainactivityextendsActivity {PrivateHandler Handler =NewHandler () { Public voidhandlemessage (android.os.Message msg) {//Child threads perform time-consuming operations completion notification main threadToast.maketext (mainactivity. This, "All Tasks Completed", Toast.length_short). Show (); //gets the handler of the child thread and sends a message to the looper of the child threadLooperthread.gethandler (). Sendemptymessage (1);    };    }; PrivateMylooperthread Looperthread; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); //initializing a looper in a child threadLooperthread =NewMylooperthread (handler); //turn on Looper in a sub-threadLooperthread.start (); //Initializes a child thread that is used to send a message to the child thread where Looper starts itMyThread thread =NewMyThread (Looperthread);    Thread.Start (); }}

      Focus on the OnCreate method, initialize a looper thread, pass in the current main thread of the handler, and then let another child thread Cheng a message to the Looper line, perform time-consuming tasks, looper thread time-consuming task execution, Take the main thread incoming handler to the main thread to send a message, the last main thread of the Handlmessage () method to receive messages, toast out, completed the main thread to sub-thread between the message docking

       
  4. Finally, summarize
    1. When handler is created, it binds to the current thread, sending a message to a thread, and getting the hanler of the thread to send a message.
    2. The Activitythread default in the main thread helps us create a looper and MessageQueue, so we don't need to create it manually, if we need to create a handler in a child thread, The child thread must also have a looper and MessageQueue corresponding to it, all, the child thread can have handler, only we manually create a Looper (MessageQueue is automatically created in the Looper constructor method)
    3. Try not to take any time-consuming actions in the handlmessage of the main thread, because it is easy to cause the main thread to block (UI thread 5 seconds, service 10 seconds)
    4. Handler Looper MessageQueue three combination, and the thread pool is particularly similar, you can use this to maintain a similar to the thread pool framework to handle time-consuming multi-threading operations, such as the network to download multiple images, etc.

Create handler and Looper in child threads and interact with the main thread

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.