Android_handler (2), android_handler
In this record, in the android message mechanism, WorkThread simulates the steps of accessing data to the network, obtaining the data, returning the message and sending it to MainThread, and modifying the text of TextView. (MainThread worker WorkThread ).
Steps:
1. Create a handler object in MainThread and rewrite the handlemessage () method.
2. WorkThread calls the sendMessage () method of handermessage () to send a message to the message queue.
3. logoff retrieves the message object in the message queue and submits it to the handlemessage () method of MainThread for processing.
Code:
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"/>
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. currentThread (). getName (); // simulate access to the network, so when the Thread is sleeping, first sleep for 2 seconds. try {Thread. sleep (2*1000);} catch (InterruptedException e) {e. printStackTrace ();} // The value of variable s, simulating the data obtained from the network String s = "data obtained from the network"; // textView. setText (s); this method is incorrect, because in the android system, only the mainthread can operate UIMessage msg = handler. obtainMessage (); msg. obj = s; // The sendMessage () method, whether sent in the main thread or in the workers thread. sendMessage (msg );}}}
Effect: