There are often problems with Android projects that update the UI after a time-consuming operation in a child thread, and then summarize the updated methods for some of the projects that you have experienced:
Reference:Android sub-threading
Method One: With handler
1, the main thread defined handler:
Handler Mhandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg); switch ( Msg.what) {Case 0://completes the main interface update, gets the data String "= (string) msg.obj;updateweather (); Textview.settext (data); Break;default: break;}};
2, the child thread sends the message, notifies handler to complete the UI update:
private void Updateweather () {New Thread (new Runnable () {@Overridepublic void Run () {//time-consuming operation, sending a message to handler after completion, completing UI update ; mhandler.sendemptymessage (0);//requires data transfer, using the following method; message msg =new message (); msg.obj = "data";//Can be a basic type, can be an object, can be a list, map, etc. ; Mhandler.sendmessage (msg);}}). Start ();}
The handler object of method one must be defined in the main thread, if multiple classes call each other directly, it is not very convenient to pass the Content object or call through the interface;
Update the UI through the Runonuithread () method in a child thread: Method Two: Update with Runonuithread
New Thread () {public void run () {///Here is a time-consuming operation, update Ui;runonuithread (new Runnable () {@Overridepublic void Run () {// Update Uiimageview.setimagebitmap (bitmap);}});}. Start ();
If it is in a non-contextual class (Activity), it can be invoked by passing the context;
Activity activity = (activity) imageview.getcontext (); Activity.runonuithread (new Runnable () {@Overridepublic void run ( ) {Imageview.setimagebitmap (bitmap);}});
This method is more flexible to use, but if the thread is defined elsewhere, the activity object needs to be passed;
Method Three: View.post (Runnable R)
Imageview.post (New Runnable () {@Overridepublic void run () {imageview.setimagebitmap (bitmap);}});
This method is simpler, but it needs to pass the view to be updated;
Ways to update the UI in an Android sub-thread