In Android, it is not safe to update UI controls in a non-main thread, and the app will be crash directly at run time, 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 the button to change the content of TextView, button click Time to create a new process, the UI control in the process to modify.
1 Public classMainactivityextendsActivityImplementsOnclicklistener {2 Private Static Final intUpdate_text = 1;3 PrivateButton send;4 PrivateTextView TV;5 6 PrivateHandler HD =NewMyHandler ();7 8 @Override9 protected voidonCreate (Bundle savedinstancestate) {Ten Super. OnCreate (savedinstancestate); One Setcontentview (r.layout.activity_main); ASend =(Button) Findviewbyid (r.id.bt_sendmessage); -TV =(TextView) Findviewbyid (r.id.tv_text); -Send.setonclicklistener ( This); the } - - @Override - Public voidOnClick (View v) { + Switch(V.getid ()) { - CaseR.id.bt_sendmessage: + NewThread (NewRunnable () { A @Override at Public voidRun () {//Create a new thread and create a new message object that sends the message with the handler object -Message msg =NewMessage (); -Msg.what = Update_text;//a user-defined value that identifies different types of messages -Hd.sendmessage (msg);//Send Message - } - }). Start (); in Break; - to default: + Break; - } the } * $ //defines an inner class that inherits from Handler, and overrides the Handlemessage method to handle messages passed by a child thread .Panax Notoginseng classMyHandlerextendshandler{ - @Override the Public voidhandlemessage (Message msg) { + Super. Handlemessage (msg); A Switch(msg.what) { the CaseUpdate_text://modify the UI control after receiving the message +Tv.settext ("Ice-Jade is a pig!")); - Break; $ $ default: - Break; - } the } - }Wuyi}
Understanding: Now defines an inner class in the main activity, inherits from Handler, and overrides the Handlemessage method in the handler, which is an empty method in handler, which facilitates the programmer to customize the contents of the message. Then in the OnCreate method, get the button and add a click event, add a thread in the event, use the message class to encapsulate a message, and then send the message with the handler object, The Handlemessage method of the handler object is called to achieve the effect of changing the contents of the TextView.
Android Development Learning path-Update UI with handler and message