Android_handler (1)
It's just a simple example of handler. The purpose is to have a preliminary contact with handler.
Add a button on layout, click the button, and print the data transmitted using handler. (All are running on mainthread)
1. layout:
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 a user clicks the button, we create a Message object and use Handler to send the object Message msg = handler. obtainMessage (); // (obtainMessage obtains the message object) msg. what = 21; handler. sendMessage (msg); // The above line of code places the message object in the message queue, and then // 1. logoff will retrieve the message object from the message queue. // 2. logoff will find the Handler object corresponding to the message object // 3. logoff will call the handlerMessage (Message msg) method of the Handler object to process the Message object} class FirstHandler extends Handler {@ Overridepublic void handleMessage (Message msg) {int what = msg. what; System. out. println (What is: + what );}}}
Effect: