Just a simple example of handler, the aim is to have a preliminary contact with handler.
Add a button to the layout, click on it, and print out the data transmitted using handler. (both are running in Mainthread)
1. Layout:
<button android:id= "@+id/buttonid" android:layout_width= "wrap_content" android:layout_height= " Wrap_content " android:text=" @string/hello_world "/>
2. Activity:
Package Com.away.b_06_handler;import Android.app.activity;import Android.os.bundle;import Android.os.Handler; 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 Buttonlistener ()); handler = new Firsthandler ();} Class Buttonlistener implements Onclicklistener {@Overridepublic void OnClick (View v) {//When the user taps the button, we create a message object, and use handler to send the object message msg = Handler.obtainmessage (); (Obtainmessage gets the message object) Msg.what = 21;handler.sendmessage (msg);//The above line of code places the Message object in the message queue, and//1.Looper will be from the message queue, Remove the Message object.//2.Looper will find the handler object that corresponds to the Message object//3.Looper will call the handler object Handlermessage (Message msg) method for processing the messaging object}}class Firsthandler extends Handler {@Overridepublic void Handlemessage (Message msg) {int what = Msg.what; System.out.println ("What's:" + What);}}
Effect:
Android_handler (i)