In this record Android messaging mechanism, Mainthread sends a message to Workthread. (Mainthread→workthread)
Steps:
1. Prepare Looper objects
2. Generate the handler object in a child thread
3. Send Message in Mainthread
Code:
Layout
<button android:id= "@+id/buttonid" android:layout_width= "wrap_content" android:layout_height= " Wrap_content " android:text=" send Message "/>
activity:
Package Com.away.b_08_handler03;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 button;private Handler Handler, @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); button = (button) Findviewbyid (R.id.buttonid); Button.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {System.out.println ("OnClick:" + Thread.CurrentThread (). GetName ()); Message msg = Handler.obtainmessage (); Handler.sendmessage (msg);}}); Workerthread wt = new Workerthread (); Wt.start ();} Class Workerthread extends thread {@Overridepublic void run () {//Prepare Looper object Looper.prepare ();//In Workers Thread, Generates an Handler object, implemented with an anonymous inner class Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {System.out.println ("Workerthread:" + thread.currentthread (). GetName ()); System.out.println ("received the Message Object!!!");}};/ /After calling Looper's Loop method, the Looper object will continuously remove the message object from the message queue and call handler's Handlemessage () method to process the message object//If there are no objects in the message queue, the thread is blocked. Looper.loop ();}}}Effect:
Android_handler (iii)