Go from the first line of code-android
Android is not allowed to perform UI operations on child threads. The asynchronous message processing mechanism provided by Android is required to perform time-consuming operations on the child threads and then update the corresponding UI controls based on the results of the task execution.
The code is as follows:
1 Public classMainactivityextendsActivityImplementsOnclicklistener {2 Private Static Final intUpdate_text=1;3 PrivateTextView TextView;4 PrivateButton CHANGETEXTBT;5 PrivateHandler handler=NewHandler () {6 Public voidhandlemessage (Message msg) {7 Switch(msg.what) {8 CaseUpdate_text:9Textview.settext ("Nice-Meet You");Ten Break; One default: A Break; - } - }; the }; - - @Override - protected voidonCreate (Bundle savedinstancestate) { + Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); +textview=(TextView) Findviewbyid (R.id.textview); Achangetextbt=(Button) Findviewbyid (R.ID.CHANGTEXTBT); atChangetextbt.setonclicklistener ( This); - } - - @Override - Public voidOnClick (View v) { - Switch(V.getid ()) { in CaseR.ID.CHANGTEXTBT: - NewThread (NewRunnable () { to @Override + Public voidrun () { -Message message=NewMessage (); themessage.what=Update_text; * handler.sendmessage (message); $ }Panax Notoginseng }). Start (); - Break; the + default: A Break; the } + } -}
A new handler object is added, and the Handlermessage () method of the parent class is overridden to handle the specific message. If you find that the What field of the message is Update_text, the TextView is updated.
The button's Click event, without direct manipulation of the UI, creates a Message (Android.os.Message) object and designates its what field as Update_text. Then call handler's SendMessage () method to send the message out. Soon, handler receives this message and processes it in the Handlermessage () method. The code in the Handlermessage () method is now running in the main thread, so you can update the UI. Next, judging by what field the message carries, if you log in to Update_text, update the contents of TextView display to meet.
Android Development Update UI in child threads