Android--Looper.prepare () and Looper.loop ()-in-depth version

Source: Internet
Author: User


The Looper class in Android is a class used to encapsulate message loops and message queues for message processing in Android threads. Handler can actually be seen as a tool class for inserting messages into message queues.


(1) The Looper class is used to open a message loop for a thread. By default, the newly born thread in Android does not have a message loop turned on. (except for the main thread, the main thread system will voluntarily create a Looper object for it to turn on the message loop.) The Looper object holds messages and events through MessageQueue. A thread can have only one looper and one MessageQueue.


(2) It is generally through handler object to interact with the Looper.     Handler can be seen as an interface to the Looper to send messages and define processing methods to the specified looper. By default, handler is bound to the looper of the thread that is defined, for example, handler is defined in the main thread, which is the looper binding to the main thread. MainHandler = new Handler () is equivalent to new Handler (Looper.mylooper ()). Looper.mylooper (): Gets the Looper object of the current process, similar to the Looper.getmainlooper () Gets the Looper object for the main thread.


(3) in the non-main thread, the direct new Handler () will report an error such as the following: E/androidruntime (6173): uncaught handler:thread Thread-8 exiting due to uncaught ex Ception E/androidruntime (6173): Java.lang.RuntimeException:Can ' t create handler inside thread that have not called Looper . Prepare () reason is that Looper objects are not created by default in the main thread, and Looper.prepare () is required to enable Looper first.


(4) Looper.loop (); Let Looper start work, take messages from the message queue, and process messages.


Note: code written after Looper.loop () will not be executed, the function should be inside a loop, and the loop will not abort until the Mhandler.getlooper (). Quit () is called.
(5) based on the above knowledge, the main thread can be implemented to send messages to the child thread (not the main threads).
declare the Mhandler in the following example as a class member, and the main thread can send messages through Mhandler. An introduction to Looper in the official Android documentation: Class used to run a message loop for a thread. Threads By default does not has a message loop associated with them; To create one, call prepare () the thread, the-is-to-run the loop, and then loops () to the IT process messages until the Loop is stopped.
Most interaction with a message loop is through the Handler class.

This was a typical example of the implementation of a Looper thread, using the separation of prepare () and loop () to create An initial Handler to communicate with the Looper.


Class Looperthread extends Thread{public Handler mhandler;public void Run () {looper.prepare (); mhandler = new Handler () {PU Blic void Handlemessage (Message msg) {//Process incoming messages here}}; Looper.loop ();}

It is assumed that Message Queuing is created using Looper.prepare () and Looper.loop () in the thread to allow the message processing to complete in that thread .


Android Handlerthread use small case

Previously, the handler and Looper message queues were studied, except that the handler in Android was not running on another thread, or in the main UI thread, and it was necessary to use the Handlerthread to implement the other threads. When using Handlerthread, you need to implement the callback interface to override the Handlermessage method to handle your own logic in the Handlermessage method. Down to give a sample program.

Layout file is very easy, just a button to start the Hanldertread thread

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" fill_parent "    android:layout_height=" fill_parent "    android:o rientation= "vertical" >    <textview        android:layout_width= "fill_parent"        android:layout_height= " Wrap_content "        android:text=" @string/hello "/>    <button        android:id=" @+id/handlerthreadbtn "        Android:layout_width= "Wrap_content"        android:layout_height= "wrap_content"        android:text= " Starthandlerthread "/></linearlayout>

Activity codes such as the following:

Package Com.tayue;import Android.app.activity;import Android.os.bundle;import android.os.handler;import Android.os.handler.callback;import Android.os.handlerthread;import Android.os.message;import Android.view.View; Import Android.view.view.onclicklistener;import android.widget.button;/** * * @author Xionglei * */public class TestHand     Leractivity extends Activity implements onclicklistener{public Button handlerthreadbtn;    Myhandlerthread Handlerthread;        Handler Handler; /** called when the activity is first created.        */@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                The name of the print UI thread System.out.println ("onCreate currentthread =" + Thread.CurrentThread (). GetName ());                Setcontentview (R.layout.main);        HANDLERTHREADBTN = (Button) Findviewbyid (R.ID.HANDLERTHREADBTN);                Handlerthreadbtn.setonclicklistener (this); Handlerthread = new Myhandlerthread ("Myhanler");        Handlerthread.start (); Note: This must be used to handler this constructor, because the need to callback in, so that their own handlerthread handlermessage to replace handler native Handlerthread handler           = New Handler (Handlerthread.getlooper (), handlerthread);    } @Override public void OnClick (View v) {//click button to turn on thread handler.sendemptymessage (1); } private class Myhandlerthread extends Handlerthread implements Callback {public Myhandlerthread (Strin        G name) {super (name);  } @Override public boolean handlemessage (Message msg) {//Print thread name System.out.println ("            Handlemessage CurrentThread = "+ Thread.CurrentThread (). GetName ());        return true; }                }         }

Click button to print the log such as the following (click here 3 times) 07-06 09:32:48.776:i/system.out (780): onCreate CurrentThread = main 07-06 09:32:55.076:i/s Ystem.out (780): handlemessage CurrentThread = Myhanler 07-06 09:32:58.669:i/system.out (780): HandleMessage CurrentThre AD = Myhanler 07-06 09:33:03.476:i/system.out (780): handlemessage CurrentThread = Myhanler

Handlerthread is so simple.

Of course, Android itself also has asynchronous thread handler, is Asynctask, this class is encapsulated Handlerthread and handler to implement asynchronous multithreading operation.

Same can be used:

Private Boolean iscancel = false;                    The user manually cancels the login flag bit handlerthread = new Handlerthread ("Myhandlerthread");                    Handlerthread.start ();                Handler = new MyHandler (Handlerthread.getlooper ());                            Join the thread object that will be running to the thread queue Handler.post (new Runnable () {@Override                                public void Run () {Message message = Handler.obtainmessage (); UserBean user = Bbs.getinstance ().                                Login (username, password);//time-consuming task Bundle B = new bundle ();                                B.putserializable ("user", user);                                Message.setdata (b); Message.sendtotarget ();                            or use Handler.sendmessage (message);    }                        });       Class MyHandler extends Handler {public MyHandler (Looper Looper) {super (Looper);     } @Override public void Handlemessage (Message msg) {if (Iscancel = = False) {                    Code Bundle B = Msg.getdata () that operates the UI thread;                                     UserBean user = (UserBean) b.get ("User");           ......               }   }    }


Android--Looper.prepare () and Looper.loop ()-in-depth version

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.