This article is about Workthread simulation to the network to access the data, after obtaining the data, the return message is sent to Mainthread, and the text of the TextView is modified.
1. Layout:
<textview android:id= "@+id/textviewid" android:layout_width= "match_parent" android:layout_ height= "Wrap_content" android:text= "Data"/> <button android:id= "@+id/buttonid" android: Layout_width= "Match_parent" android:layout_height= "wrap_content" android:layout_below= "@id/textviewid" android:text= "Send Message"/>
2. Activity:
Package Com.away.b_07_handler02;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;import Android.widget.textview;public class Mainactivity extends Activity {private TextView Textview;private Button button;private Handler Handler; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); TextView = (TextView) Findviewbyid ( R.ID.TEXTVIEWID); button = (button) Findviewbyid (r.id.buttonid); handler = new MyHandler (); Button.setonclicklistener ( New Buttonlistener ());} Class MyHandler extends Handler {@Overridepublic void Handlemessage (Message msg) {System.out.println ("handlermessage-- -->>: "+ thread.currentthread (). GetName ()); string s = (string) msg.obj;textview.settext (s);}} Class Buttonlistener implements Onclicklistener {@Overridepublic void OnClick (View arg0) {threAd t = new Networkthread (); T.start ();}} Class Networkthread extends Thread {@Overridepublic void run () {System.out.println ("network---->>:" + Thread.curr Entthread (). GetName ());//analog access to the network, so that when the thread sleeps, first sleep for 2 seconds try {thread.sleep (2 *);} catch (Interruptedexception e) { E.printstacktrace ();} The value of the variable s, which simulates the data obtained from the network string s = "Data obtained from the network";//Textview.settext (s); This is wrong because in the Android system, only Mainthread can operate uimessage msg = Handler.obtainmessage (); msg.obj = s;//sendMessage () method, Whether it is sent in the main thread or in the workers thread, it is handler.sendmessage (msg);}}
1
Android_handler (b)