In the Android development process, it is often necessary to update the UI of the interface. For example, the network request operation, some time-consuming operation can not be placed in the UI thread to run, need to put on the child thread, and the child thread can not update UI interface, this is we need to introduce a handler, message processing mechanism. The update UI is to be updated by the main thread (UI thread), which is the UI thread update. If you update the page directly in a thread other than the main thread, the error often appears. Throw exception: Android.view.viewroot$calledfromwrongthreadexception:only The original thread that created a view hierarchy can tou Ch its views.
Only the thread that originally created the view hierachy can modify its view
There are two ways to update the UI interface. 1.create an instance of the handler class, and then implement the Handlemessage () callback function in this class to manipulate the update UI interface in this callback function, and then how does it know when to update the interface? You need to send a message to the message queue via handler. Mhandler.sendemptymessage (what); To identify what UI interface is updated specifically.
Private Handler Mhandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg); Switch (msg.what) {case GET2CODE_SUCCESS:dialog.dismiss (); Set2codeshow (); break;case CONN_FAILED:dialog.dismiss (); Set2codeshow (); Toast.maketext (Goodsinfo.this, "Connection Failed", Toast.length_short). Show (); break;default:break;}}};
Mhandler.sendemptymessage (get2code_success); or create a Message object, message msg = new Message (); msg.what=get2code_success; then through Mhandler.sendmessage (msg), send the message to the message queue, of course, you can also send the object data, that is, with msg.obj= object to send objects.
2, the use of Activity.runonuithread (new Runnable{run () {}}) to update the required UI code in the Run () method, the fact that the principle is to send a message through handler to the main thread.
Two ways to update the UI for Android--handler and Runonuithread ()