UI update method in the android thread and android thread
This problem is often encountered in Android projects. After time-consuming operations are completed in the Child thread, you need to update the UI. The following describes the updated methods for some projects you have experienced:
Reference: Android sub-Thread
Method 1: Use Handler
1. Handler defined in the main thread:
Handler mHandler = new Handler () {@ Overridepublic void handleMessage (Message msg) {super. handleMessage (msg); switch (msg. what) {case 0: // complete the main interface update and get the data String data = (String) msg. obj; updateWeather (); textView. setText (data); break; default: break ;}}};
2. Send a message to the sub-thread to notify Handler to complete UI update:
Private void updateWeather () {new Thread (new Runnable () {@ Overridepublic void run () {// time-consuming operation. After completion, send a message to Handler to complete UI update; mHandler. sendEmptyMessage (0); // use the following method to transmit data; Message msg = new Message (); msg. obj = "data"; // It Can Be A basic type, an object, a List, a map, or mHandler. sendMessage (msg );}}). start ();}
The Handler object of method 1 must be defined in the main thread. If multiple classes call each other directly, it is not very convenient. You need to pass the content object or call it through the interface;
Update the UI using the runOnUiThread () method in the Child thread: Method 2: update with runOnUiThread
New Thread () {public void run () {// this operation is time-consuming. After completion, the UI is updated. runOnUiThread (new Runnable () {@ Overridepublic void run () {// update UIimageView. setImageBitmap (bitmap );}});}}. start ();
If it is in a non-context class (Activity), it can be called by passing context;
Activity activity = (Activity) imageView.getContext();activity.runOnUiThread(new Runnable() {@Overridepublic void run() {imageView.setImageBitmap(bitmap);}});
This method is flexible, but if the Thread is defined elsewhere, the Activity object needs to be passed;
Method 3: View. post (Runnable r)
imageView.post(new Runnable(){@Overridepublic void run() {imageView.setImageBitmap(bitmap);}});
This method is simpler, but the View to be updated must be passed;