SoFunction
Updated on 2025-04-09

Android AsyncTask detailed introduction

Comparison of AsyncTask and Handler

1) The principles of AsyncTask implementation and the advantages and disadvantages of application

AsyncTask is a lightweight asynchronous class provided by Android. It can directly inherit AsyncTask, implement asynchronous operations in the class, and provide the interface to feedback the degree of current asynchronous execution (UI progress update can be achieved through the interface), and finally feedback the results of the execution to the UI main thread.

Advantages of use:

  • Simple, fast
  • The process is controllable

Disadvantages of use:

  • It becomes complicated when using multiple asynchronous operations and requiring Ui changes.

2) Principles and advantages and disadvantages of Handler asynchronous implementation

When the Handler is asynchronously implemented, it involves four objects: Handler, Looper, Message, and Thread. The process of implementing asynchronous is that the main thread starts Thread (child thread) àthread (child thread) and generates Message-àLooper to obtain Message and passes it to Handler àHandler to obtain Message in Looper one by one, and makes UI changes.

Advantages of use:

  • Clear structure and clear functional definition
  • Simple and clear when multiple background tasks

Disadvantages of use:

  • When processing asynchronously in a single background, it seems that there is too much code and the structure is too complex (relative)

Introduction to AsyncTask

Android's AsyncTask is lighter than Handler and is suitable for simple asynchronous processing.

First of all, it is clear that the reason why Android has Handler and AsyncTask is to not block the main thread (UI thread), and UI updates can only be completed in the main thread, so asynchronous processing is inevitable.

In order to reduce the difficulty of this development, Android provides AsyncTask. AsyncTask is an encapsulated background task class, as its name implies, asynchronous tasks.

AsyncTask is directly inherited from the Object class, and its location is. To work with AsyncTask we need to provide three generic parameters and overload several methods (at least one overload).

AsyncTask defines three generic types: Params, Progress, and Result.

  • Params Input parameters for starting task execution, such as the URL of the HTTP request.
  • Progress Backend Task Percentage Execution.
  • Result The final result returned by the task in the background, such as String.

Students who have used AsyncTask know that a minimum of asynchronous loading of data must be rewrite the following two methods:

  • doInBackground(Params…) is executed in the background, and all the time-consuming operations can be placed here. Note that you cannot directly operate the UI here. This method is executed in a background thread and completes the main work of the task, which usually takes a long time. During execution, publicProgress (Progress…) can be called to update the progress of the task.
  • onPostExecute(Result) is equivalent to the way Handler handles the UI. Here, you can use the result processing operation UI obtained on doInBackground. This method is executed in the main thread, and the result of task execution is returned as a parameter of this method

If necessary, you have to rewrite the following three methods, but it is not necessary:

  • onProgressUpdate(Progress…)   You can use the progress bar to increase user experience. This method is executed in the main thread and is used to display the progress of task execution.
  • onPreExecute()                        This is the interface when the end user calls Excute. When this method is started to be called before the task is executed, the progress dialog box can be displayed here.
  • onCancelled()                                                                                                                            �

Using the AsyncTask class, the following are several guidelines that must be followed:

  • An instance of a Task must be created in the UI thread;
  • The execute method must be called in the UI thread;
  • Do not manually call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) methods;
  • The task can only be executed once, otherwise an exception will appear when multiple calls are called;

An example of a super simple understanding of AsyncTask:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:andro 
  android:orientation="vertical" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  > 
  <TextView  
  android: 
  android:layout_width="fill_parent"  
  android:layout_height="wrap_content"  
  /> 
  <ProgressBar  
  android: 
  android:layout_width="fill_parent"  
  android:layout_height="wrap_content"  
  style="?android:attr/progressBarStyleHorizontal"  
  /> 
  <Button 
  android: 
  android:layout_width="fill_parent"  
  android:layout_height="wrap_content"  
  android:text="Update progressbar" 
  /> 
</LinearLayout> 

package ; 
 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
 
public class MainActivity extends Activity { 
  private Button button; 
  private ProgressBar progressBar; 
  private TextView textView; 
   
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    (savedInstanceState); 
    setContentView(); 
     
    button = (Button)findViewById(.button03); 
    progressBar = (ProgressBar)findViewById(.progressBar02); 
    textView = (TextView)findViewById(.textView01); 
     
    (new OnClickListener() { 
       
      @Override 
      public void onClick(View v) { 
        ProgressBarAsyncTask asyncTask = new ProgressBarAsyncTask(textView, progressBar); 
        (1000); 
      } 
    }); 
  } 
} 
 

package ; 
 //Simulate network environmentpublic class NetOperator { 
   
  public void operator(){ 
    try { 
      //Sleep for 1 second      (1000); 
    } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      (); 
    } 
  } 
 
} 

ProgressBarAsyncTask .java

package ; 
import ; 
import ; 
import ; 
 
/**
  * After generating an object of this class and calling the execute method
  * The first thing to execute is the onProExecute method
  * Next, execute the doInBackgroup method
  *
  */ 
public class ProgressBarAsyncTask extends AsyncTask<Integer, Integer, String> { 
 
  private TextView textView; 
  private ProgressBar progressBar; 
   
   
  public ProgressBarAsyncTask(TextView textView, ProgressBar progressBar) { 
    super(); 
     = textView; 
     = progressBar; 
  } 
 
 
  /**
    * The Integer parameter here corresponds to the first parameter in AsyncTask
    * The String return value here corresponds to the third parameter of AsyncTask
    * This method does not run in the UI thread and is mainly used for asynchronous operations. All spaces in the UI cannot be set and modified in this method.
    * However, you can call the publishProgress method to trigger onProgressUpdate to operate on the UI
    */ 
  @Override 
  protected String doInBackground(Integer... params) { 
    NetOperator netOperator = new NetOperator(); 
    int i = 0; 
    for (i = 10; i <= 100; i+=10) { 
      (); 
      publishProgress(i); 
    } 
    return i + params[0].intValue() + ""; 
  } 
 
 
  /**
    * The String parameter here corresponds to the third parameter in AsyncTask (that is, the return value of doInBackground)
    * After the doInBackground method is executed, it is running and running in the UI thread. The UI space can be set.
    */ 
  @Override 
  protected void onPostExecute(String result) { 
    ("Async operation execution ends" + result); 
  } 
 
 
  //This method runs in the UI thread and runs in the UI thread. The UI space can be set.  @Override 
  protected void onPreExecute() { 
    ("Start execution of asynchronous threads"); 
  } 
 
 
  /**
    * The Intege parameter here corresponds to the second parameter in AsyncTask
    * In the doInBackground method, every time the publishProgress method is called, the onProgressUpdate execution will be triggered.
    * onProgressUpdate is executed in a UI thread, and all operations can be performed on the UI space.
    */ 
  @Override 
  protected void onProgressUpdate(Integer... values) { 
    int vlaue = values[0]; 
    (vlaue); 
  }  
} 

Original link: /devinzhang/archive/2012/02/13/

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.