To do a simple little demo about Handler,looper,message, a button on the main interface of the code, click Send Message (accumulate) to the thread's Looper loop, and then print it out in Logcat:
Package Zhangphil.looper;import Android.os.bundle;import Android.os.handler;import android.os.looper;import Android.os.message;import Android.util.log;import Android.view.view;import Android.widget.button;import Android.app.activity;public class Mainactivity extends Activity {private Handler mhandler;private final int message_what = 101; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); final button button = (button) Findviewbyid (R.id.button); Button.setonclicklistener (New View.onclicklistener () {private int count = 0; @Overridepublic void OnClick (View v) { Mhandler.obtainmessage (Message_what, Count). Sendtotarget (); Button.settext ("Sent" + count); count++;}); New Messagereceivethread (). Start ();} Private class Messagereceivethread extends Thread {@Overridepublic void run () {looper.prepare (); mhandler = new Handler () { @Overridepublic void Handlemessage (Message msg) {switch (msg.what) {case message_what:string TeXT = Msg.obj + ""; LOG.D ("Received--", text); break;}}; Looper.loop ();}}}
Activity_main.xml files required by Mainactivity.java:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_ Parent " android:layout_height=" match_parent "> <button android:id=" @+id/button " android: text= "Send Message" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android: Layout_centerhorizontal= "true" android:layout_centervertical= "true"/></relativelayout>
Android Handler,looper,message