Android updates the UI using handler, runOnUiThread (), and runonuithread
During Android development, you often need to update the UI of the interface. For example, network request operations and some time-consuming operations cannot be run in the UI thread, but must be placed in the subthread, And the subthread cannot update the UI interface. This is a Handler that needs to be introduced, message Processing Mechanism. UI update is performed by the main thread (UI thread), that is, UI thread update. If the page is directly updated in a thread other than the main thread, an error is often reported. Throw an exception: android. view. ViewRoot $ CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Only the thread that originally created the view hierachy can modify its view)
The following two methods are provided to update the UI. 1. Create a Handler class instance and implement the handleMessage () callback function in this class. In this callback function, perform operations to update the UI interface, then how does it know when to update the interface? You need to send a message to the Message Queue through Handler. MHandler. sendEmptyMessage (what); to identify the UI page for specific updates.
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 use mHandler. sendMessage (msg); to send messages to the Message Queue. Of course, object data can also be sent, that is, msg. obj = Object to send objects.
2. Use Activity. runOnUiThread (new Runnable {run () {}}) creates the UI code required for updating in the run () method. In fact, this principle is to send messages to the main thread through Handler.