In Android, it's not safe to update UI controls in a non main thread, and app runs directly crash, so when we need to update UI controls in a non main thread, we need to use handler and message to implement
demo, Use to a button and a TextView, click on the button to change the content of the TextView, button click to create a new process, the UI control in the process to modify.
public class Mainactivity extends activity implements Onclicklistener {private static final int update_text = 1;
Private Button send;
Private TextView TV;
Private Handler HD = new MyHandler ();
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Send = (Button) Findviewbyid (r.id.bt_sendmessage);
TV = (TextView) Findviewbyid (R.id.tv_text);
Send.setonclicklistener (this); @Override public void OnClick (View v) {switch (V.getid ()) {case R.id.bt_sendmessage:new Thread (new Runnable () {@Override public void run () {//Create a new thread and create a new object for the message that is sent with the handler object.
Ssage msg = new Message (); Msg.what = Update_text; A user-defined value that identifies a different type of message hd.sendmessage (msg);
Send Message}}). Start ();
Break
Default:break; }//define an inner class inherits from Handler, and the overlay Handlemessage method is used to process child threads passing overMessages class MyHandler extends handler{@Override public void Handlemessage (msg) {SUPER.HANDLEMESSAG
E (msg); Switch (msg.what) {case Update_text://After receiving the message, modify the UI control Tv.settext ("The modification was successful!")
");
Break
Default:break;
}
}
}
}
Understanding: First define an inner class in the main activity, inherit from handler, and overwrite the Handlemessage method in handler, which is an empty method in handler, which makes it easier for us to customize the content of the message. Then in the OnCreate method, get the button and add a click event, add a thread to the event, use the message class in the thread, and then send the message using the handler object. The Handlemessage method of the handler object is invoked to change the effect of the TextView content.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.