SoFunction
Updated on 2025-03-02

Examples of several ways Android updates UI in child threads

This article introduces several examples of Android's methods to update the UI in child threads. I will share it with you, as follows:

Method 1: Handler and Message

① Instantiate a Handler and override handlerMessage() method

private Handler handler = newHandler() {
    public void handleMessage(Message msg) {
          // Process messages    (msg);
    switch () {
    case 1:
      ("Click to install");
      break;
    case 2:
      ("Open");
      break;
    }
    };
 }; 

② Get or create a message in the child thread and send it using the handler object.

Message msg = ();
 = 1;
(msg);

Method 2: Call the Runnable action method directly in the child thread

runOnUiThread(new Runnable() {
  @Override
  public void run() {
    // Update the UI operation  }
});

Method 3: Call the post() method of View in the child thread

(new Runnable() {          
  @Override
  public void run() {
    // Update the UI    (“renewUI”);
  }});

Method 4: Call (Runnabe, long) in child thread

Three pairs of supplementary methods, long parameters are used to determine how long it takes to run the background process.

Method 5: Handler's post() method

① Create a Handler member variable

private Handler handler = new Handler();

② Mobilize the post() method in the child thread

(new Runnable() {           
  @Override
  public void run() {
    // Update the UI   (“renewUI”);
  }});

Method 6: AsyncTask

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> 
 //The types of Params, Progress, and Result parameters are declared here {
   //Because there is no need to use the onPreExecute callback method here, so this method is not added   
   //The purpose of background threads is to have more URL download data    protected Long doInBackground(URL... urls) {
      int count = ;//urls is an array, more than one download link      long totalSize = 0;//Downloaded data     for (int i = 0; i < count; i++) {
       //Download is a class used for download and has nothing to do with AsyncTask. You can ignore its implementation       totalSize += (urls[i]);
       publishProgress((int) ((i / (float) count) * ));//Update the download progress       // Escape early if cancel() is called
       if (isCancelled()) break;
     }
     return totalSize;
   }
 
   //Update download progress   protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
   }
 
   //Update the downloaded data to the UI thread   protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
   }
 }

For general, just simply update the ui, and the situation is not complicated, the use method is enough, but when the situation is relatively complicated, it is still recommended to use handler.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.