Package Com.example.looper;import Android.app.activity;import Android.os.bundle;import android.os.Handler;import Android.os.looper;import Android.os.message;import Android.view.view;import Android.view.View.OnClickListener; Import Android.widget.button;public class Mainactivity extends Activity {private Button send;private Handler handler;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); send = (Button) Findviewbyid (r.id.button1); new Thread (New MyThread ()). Start ();// The main thread has a default Loopersend.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {Message message = Message.obtain (); message.obj = "Jackson"; handler.sendmessage (message);}); public class MyThread implements runnable{@Overridepublic void Run () {//In the child thread does not have Looper concept looper.prepare ();//Loop message Queue// In child thread instantiation Handler handler = new Handler () {@Override public void Handlemessage (Message msg) { Receive main thread send in child threadsCome over the message super.handlemessage (msg); System.out.println ("--Get message-->> from the main thread" + msg.obj); } }; Looper.loop ();}}}
<relativelayout 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:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_ Horizontal_margin " android:paddingright=" @dimen/activity_horizontal_margin " android:paddingtop=" @dimen /activity_vertical_margin " tools:context=" com.example.looper.MainActivity "> <button android: Id= "@+id/button1" android:layout_width= "fill_parent" android:layout_height= "Wrap_content " Android:layout_alignparenttop= "true" android:layout_centerhorizontal= "true" android:layout_margintop = "56DP" android:text= "Send Message"/></relativelayout>
View the results of the output under Logcat
Source code Download
Handler message passing mechanism (iv) a child thread receives a message sent by the main thread