In general, when we write Android code, we will take some time-consuming operations, such as network access, disk access to a sub-thread to execute. This type of operation is often accompanied by a UI update operation. For example, to access the network to load a picture
NewThread () {@Override Public voidrun () {Try{URL URL=NewURL (path); HttpURLConnection Connection=(httpurlconnection) URL. OpenConnection ();//Set Request Mode Connection.setrequestmethod ("GET");//Set timeout time connection.setconnecttimeout (10000);intCode =Connection.getresponsecode ();if(Code = = 200) {InputStream is=Connection.getinputstream (); Bitmap Bitmap=Bitmapfactory.decodestream (IS); Iv_beauty.setimagebitmap (bitmap);} Else{Toast.maketext (Getapplicationcontext (),"Picture acquisition failed!" ", 0). Show (); } } Catch(Exception e) {Toast.maketext (Getapplicationcontext (), "Picture gets failed! ", 0). Show ();}}}. Start ();
If this is done, it will throw
10-20 02:50:38.219:w/system.err (497): android.view.viewroot$calledfromwrongthreadexception:only the original Thread that created a view hierarchy can touch it views.
The English sentence in the back is probably that only the main thread that created the UI object can modify the UI
The reason for this is that Android is not thread-safe, so Android has a mechanism to block child threads from updating components.
So we should give the UI update to the main thread to complete, how to do it, Android provides us with a set of message processing mechanism.
Its approximate implementation steps are like this
1. A child thread sends a message using the handler class, and the message is sent out of the main thread's message queue
2. Inside the main thread there is a poll called looper, which loops through the message queue
3. If Loopler finds new messages in the message queue, Android calls Handler's Handlemessage () method to process the message
This article transferred from: http://www.educity.cn/wenda/180403.html
Android.view.viewrootimpl$calledfromwrongthreadexception Error Handling