We know that handler is a transmission mechanism in Android that can transmit a wide variety of messages, making multithreading easier to use. But what I'm saying here is that we can also use handler to truncate the messages sent. The code is as follows
XML code
1 <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" 2 xmlns:tools= "/http/ Schemas.android.com/tools "3 android:layout_width=" match_parent "4 android:layout_height=" Match_parent "5 tools:context= "Com.example.android_handler2. Mainactivity "> 6 <button 7 android:id=" @+id/button "8 android:layout_width=" Fill_parent "9 android:layout_height= "Wrap_content" ten android:text= "@string/button_string" />12 </ Linearlayout>
Java code
1 packageCom.example.android_handler2; 2 3 4 5 6 7 Importandroid.app.Activity; 8 ImportAndroid.os.Bundle; 9 ImportANDROID.OS.HANDLER;10 ImportANDROID.OS.HANDLER.CALLBACK;11 ImportANDROID.OS.MESSAGE;12 ImportANDROID.VIEW.VIEW;13 ImportANDROID.VIEW.VIEW.ONCLICKLISTENER;14 ImportANDROID.WIDGET.BUTTON;15 ImportANDROID.WIDGET.TOAST;16 public class Mainactivity extends Activity implementsonclicklistener{18 Private button button = null; Handler Handler = new Handler (new Callback () {20////= If return is true, the following Handlermessage method 21 is truncated public boolean handlemessage (Message msg) {Toast.maketext (Mainactivity.this, "1" , Toast.length_long). Show (); [+] (+ }25 }) {n-public void handlemessage (Message msg) {Toast.maketext (Mai Nactivity.this, "2" , Toast.length_long). Show (); return ; }30 };31 protected void ONCR Eate (Bundle savedinstancestate) {+ Super . OnCreate (savedinstancestate); Setcontentview ( R.layout.activity_main); button = (Button) Findviewbyid (R.id.button); Button.setonclicklistener (this ) }37 @Override38 public void OnClick (View v) {handler.sendemptymessage (1 ); }42 *
Running this program we know that toast only prints 1, not two, so that 2 has been truncated.
Android in handler use of the four