Android UI Programming (5)--looper

Source: Internet
Author: User

Looper is typically a thread running in a circular queue of messages, and threads do not provide a looping message to associate them by default, that is, there is no message queue in the normal thread to correlate the message. Then if the thread wants to manage these messages, it must call Looper.prepare () in this thread to make the message queue run, and call Looper.loop () This method to keep its message queue running until it stops. And handler is a message queue an interactive message that includes sending messages to the message queue, and extracting messages from the message queue and processing them.

Summary :

Android uses a Message object to manage the message data and to send them to the message queue for management. The message object is placed into and removed from the message queue and processed by the handler object. But the outermost layer of executing these mechanisms is managed by Looper objects. As shown in the following:


message: Messages that contain the message ID, the message Processing object, and the processed data, which are processed by the MessageQueue unified queue and eventually by handler

Handler: Handler, responsible for sending and processing the message. When using handler, you need to implement the Handlemessage (Message msg) method to process a specific message, such as updating the UI, etc.

MessageQueue: Message Queuing, which holds messages sent by handler and executes according to FIFO rules. Of course, storing a message is not a meaningful preservation, but rather a concatenation of the message in the form of a linked list, waiting for the looper to be extracted

Looper: The message pump continuously extracts message execution from the MessageQueue . Therefore, a MessageQueue requires a looper to receive the message thread

Thread: threads, responsible for dispatching the entire message loop, that is, the execution site of the message loop

The message queues and message loops of the Android system are specific to the thread, a thread can exist (or can not exist) a message queue and a message loop (Looper), a message for a particular thread can only be distributed to this thread, not cross-threading, cross-process communication. and create a worker thread by default there is no message loop and Message Queuing, if you want the thread to have a queue and message loop, you need to call Looper.prepare () in the threads first to create the message queue, and then call Looper.loop () to enter the message loop.

However, activity is a UI thread that runs in the main thread. The Android system creates a message queue and message loop (Looper) for activity when it starts. When the android application process starts, it loads the Activitythread class in the process and executes the main method of the class, and the application's message loop process is implemented in this main method, that is, the UI thread has a Looper object by default. In the activity there is a default Looper object that handles the messages sent in the child thread .

Example One

androidmanifest.xml--did not make any changes to create the project default generated

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "/http Schemas.android.com/apk/res/android "package=" Com.wxl.handler_message "android:versioncode=" 1 "Android:versionnam E= "1.0" > <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "/> <applicatio"        n android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name"            Android:theme= "@style/apptheme" > <activity android:name= "com.wxl.looper.MainActivity" Android:label= "@string/app_name" > <intent-filter> <action android:name= "Androi D.intent.action.main "/> <category android:name=" Android.intent.category.LAUNCHER "/> & Lt;/intent-filter> </activity> </application></manifest> 
Activity_main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:gravity= "center"    android:orientation= "vertical"    tools:context= ". Mainactivity ">    <textview        android:id=" @+id/textview "        android:layout_width=" Wrap_content "        android:layout_height= "wrap_content"/>        <button         android:id= "@+id/button"        android: Layout_width= "Wrap_content"        android:layout_height= "wrap_content"        android:text= "send Hello World"/> </LinearLayout>
Mainactivity.java

Package Com.wxl.looper;import Android.os.bundle;import Android.os.handler;import android.os.message;import Android.view.view;import Android.widget.button;import Android.widget.textview;import Android.app.Activity;public Class Mainactivity extends Activity {private TextView textview;private Button button;private MyThread thread;private Hand    Ler handler;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        TextView = (TextView) This.findviewbyid (R.id.textview);        Button = (button) This.findviewbyid (R.id.button); Button.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated Method Stubmessage message = Message.obtain (); message.what = 1;message.obj = "Hello World"; handler.sendmessage (Message)        ;}});    thread = new MyThread (); } public class MyThread extends Thread {public MyThread () {//TODO Auto-generated constructor Stub handler = new Handler () {@Override public void Handlemessage (Message msg) {//To    Do auto-generated method stub super.handlemessage (msg);    if (1 = = Msg.what) {textview.settext ("" +msg.obj);    }    }    };}    @Override public void Run () {//TODO auto-generated Method Stub Super.run (); }    }        }
before clicking the button

after clicking the button :

This example also does not see the role of Looper, because the activity is used by the default looper. As can be seen from the above example, I did not start the mythread thread

Example Two

Modify the Mainactivity.java file

Package Com.wxl.looper;import Android.os.bundle;import Android.os.handler;import android.os.message;import Android.view.view;import Android.widget.button;import Android.widget.textview;import Android.app.Activity;public Class Mainactivity extends Activity {private TextView textview;private Button button;private MyThread thread;private Hand    Ler handler;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        TextView = (TextView) This.findviewbyid (R.id.textview);        Button = (button) This.findviewbyid (R.id.button); Button.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated Method Stubmessage message = Message.obtain (); message.what = 1;message.obj = "Hello World"; handler.sendmessage (Message)        ;}});        thread = new MyThread ();    Thread.Start (); } public class MyThread extends Thread {publicMyThread () {//TODO auto-generated constructor stub//handler = new Handler () {//@Override//public void Handleme Ssage (Message msg) {////TODO auto-generated method stub//super.handlemessage (msg);//if (1 = = Msg.what)//{    Textview.settext ("" +msg.obj);//}//}//};}    @Override public void Run () {//TODO auto-generated Method Stub Super.run ();    Handler = new Handler () {@Override public void Handlemessage (Message msg) {//TODO auto-generated method stub    Super.handlemessage (msg);    if (1 = = Msg.what) {textview.settext ("" +msg.obj);    }    }    }; }    }        }
The Mythread thread is started in the OnCreate () method of the handler initialization method thread of the Run method. At this point, the following error message appears for running the program:

A function cannot be created in a child thread, and Looper.prepare () is not called. Why does the above example put handler initialization in the Mythread constructor without a problem, and put the problem in the Run method? The reason is that the above in the Mythread constructor to initialize the handler still belong to the UI main thread of the code, through we did not start mythread threads also know. However, initializing the handler in the Run method is part of the Mythread child thread, which is instantiated in a child thread, out of the UI main thread, and does not provide looper by default. We modify the Run method in the Mythread thread and modify it as follows:

public void Run () {    //TODO auto-generated method Stub    super.run ();    Looper.prepare ();    Handler = new Handler () {    @Override public    void Handlemessage (Message msg) {    //TODO auto-generated method Stu b    super.handlemessage (msg);    if (1 = = Msg.what)    {    //textview.settext ("" +msg.obj); child threads cannot update UI    log.i ("", "" +msg.obj);    }};    Looper.loop ();    }

Click the button




Android UI Programming (5)--looper

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.