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 where 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 the Looper loop method, the Looper object will continuously remove the message object from the message queue, and then call Handler's Handlemessage () method to process the message object//Assuming that there is no object in the message queue, the thread is blocked. Looper.loop ();}}}
Effect:
So. Why do we not see Looper.prepare () and Looper.loop () calls in the demo example? The reason is that our activity is a UI thread that executes in the main thread. The Android system creates a message queue and message loop for the activity when it starts.
Welcome to AC http://blog.csdn.net/ycwol/article/details/42084905
Android_handler (iii)