SoFunction
Updated on 2025-03-02

Detailed explanation of the use of AsyncTask in Android

Detailed explanation of the use of AsyncTask in Android

1. First, let’s take a look at the introduction of AsyncTask:

Handler and AsyncTask are both methods used in android to implement asynchronous task processing; among them:

The Handler instance sends a message to the UI thread to complete the interface update,

Advantages: relatively fine control of the entire process;
Disadvantages: The code is relatively bloated, and it is difficult to accurately control threads when multiple tasks are executed at the same time;

AsyncTask: is lighter than Handler, suitable for simple asynchronous processing;

Advantages: Simple | Quick | Controllable process;
Disadvantages: It becomes complicated when using multiple asynchronous operations;

2. Definition of AsyncTask: (AsyncTask defines three generic types)

  public abstract class AsyncTask<Params,Progress,Result>{...} 

illustrate:

Params: Input parameters for starting task execution, such as: URL for HTTP request;
Progress: The percentage of background tasks executed;
Result: The final result returned by the background task execution, such as String;

3. The execution steps of AsyncTask asynchronous tasks: (The following method is executed (Params... params), rewritten in AsyncTask), the following is an introduction to the relevant methods:

    A、execute(Params... params) : 

Execute an asynchronous task, we need to call it in the UI thread to trigger the task

    B、OnPreExecute(): 

Execute(Params... params) is executed immediately after the call, which is generally used to mark the UI before executing background tasks; for example, the progress dialog box can be displayed here;

    C、doInBackground(Params.. params): 

onPreExecute() is executed after completion, in the background, and is time-consuming to process; the UI cannot be operated here, and publishProgress(Progress... values) is called during execution to update progress information;

    D、onProgressUpdate(Progress... values): 

When calling the publicshProgress(Progress... values) method to execute, the progress information is directly updated to the UI assembly; this method is executed on the main thread and is used to display the progress of task execution;

    E、onPostExecute(Result result): 

This method is executed in the main thread. When the background operation is finished, this method will be called. The calculation result is passed to this method as a parameter, and the result is displayed directly on the UI assembly.

    F、cancel(); : 

Cancel an executing task, complete it in the UI thread, and call it with the AsyncTask object, with the parameter true/false;

4. Things to note when using AsyncTask:

A. Asynchronous task instances must be created in the UI thread;
B. execute(Params... params) method must be called in the UI thread;
C. Do not manually adjust the methods onPreExecute().doInBackground().onProgressUpdate().onPostExecute();
D. Component information cannot be changed in doInBackground(Params... params);
E. A task instance can only be executed once, and an exception will be thrown if executed the second time;

5. Case: Use AsyncTask to achieve image download:

Activity class, the entrance to the main program:

  public class MainActivity extends Activity { 
 
  // Program entry  protected void onCreate(Bundle savedInstanceState) { 
    (savedInstanceState); 
    setContentView(.activity_main); 
    MyAsyncTask my = new MyAsyncTask(); 
    ("/20110927/"); 
  } 
 
} 

AsyncTask derived classes to implement asynchronous tasks:

  package ; 
 
import ; 
import ; 
import ; 
import ; 
 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
 
import ; 
import ; 
import ; 
import ; 
 
/**
  * Asynchronous tasks to achieve the acquisition of web page content
  *
  *
  * After generating an object of this class and calling the execute method
  *
  * The first thing to execute is the onProExecute() method,
  *
  * The second execution of doInBackground() method
  */ 
public class MyAsyncTask extends AsyncTask&lt;String, Integer, Bitmap&gt; { 
 
  /**
    * Execute immediately after the execute() method is executed and run in the UI thread.
    * Execute before the background task begins to identify the UI interface
    */ 
  protected void onPreExecute() { 
    (); 
    ("msg","onPreExecute()..."); 
  } 
 
  /**
    * Time-consuming tasks in the background;
    *
    * The String parameter in the method corresponds to the first parameter of AsyncTask;
    * The returned Bitmap corresponds to the third parameter of AsyncTask;
    *
    * This method does not run in UI threads and is mainly used for asynchronous operations. You can call the publishProgress() method to trigger it.
    * onProgressUpdate operates on the UI;
    *
    */ 
  protected Bitmap doInBackground(String... params) { 
    ("msg","doInBackground(String... params)..."); 
 
    try { 
 
      /* Network access method 2 */ 
      /*
       URL url = new URL(params[0]);
       HttpsURLConnection connection = (HttpsURLConnection) ();
       (); // Start connection
       int zong = ();
       InputStream is2 = ();
       */ 
 
      /* Start network access data */ 
      HttpGet hg = new HttpGet(params[0]); // Pay attention to the usage of parameters here      HttpClient hc = new DefaultHttpClient(); 
      HttpResponse hr = (hg); // Send a request and get a response 
      // Determine whether the request is successful      if(().getStatusCode() == HttpStatus.SC_OK){ 
        ("msg", "access success..."); 
        HttpEntity he = (); 
        InputStream is = (); // Get the input stream object, like a bridge        long total = (); // Total bytes of the file 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Output stream, temporary container, used to load data flowing from is 
        byte[] buffer = new byte[1024]; // Cache container, load 1024 bytes of data each time        int len = 0; // Number of bytes read each time        int curLen = 0 ; // How much data has been read 
        while((len=(buffer))!=-1){ // When len !=-1, there is still data to read          ("msg","begin read data..."+len+",total:"+total); 
          (buffer, 0, len); // Install data into temporary containers          curLen=curLen+len; // Update the read data 
          /* Display the current read progress in the UI, and the call method triggers the execution of the onProgressUpdate() method */ 
          publishProgress((int)(((float)curLen/total)*100)); 
        } 
 
        Bitmap bitmap = ((), 0, (int)total); 
        (); 
        return bitmap; 
      } 
    } catch (Exception e) { 
      (); 
    } 
 
    return null; 
  } 
 
  /**
    * Parameters in brackets: String corresponds to the third parameter of AsyncTask, that is
    * Received the result returned from doInBackground();
    * This method is executed after the doInBackground() method is executed and runs in the UI thread.
    * Can update the UI
    */ 
  protected void onPostExecute(Bitmap result) { 
    (result); 
    ("msg","onPostExecute(String result)..."+()); 
  } 
 
 
  /**
    * Integer in method brackets corresponds to the second parameter in AsyncTask;
    * Executes each time publishProgress() is called in doInBackground();
    * This method is in the UI thread, so it can be used to update the UI
    */ 
  protected void onProgressUpdate(Integer... values) { 
    (values); 
 
    ("msg","onProgressUpdate(Integer... values)..."+values[0]); 
  } 
 
 
  /**
    * Download pictures
    */ 
  public HttpURLConnection downPic(String urltemp){ 
 
    try { 
      URL url = new URL(urltemp); // Determine the connection address      // Open a connection      HttpURLConnection connection = (HttpURLConnection) (); 
      (); // Start the connection      return connection; 
    } catch (Exception e) { 
      (); 
    } 
    return null; 
  } 
 
 
 
} 


The above is an application example of Android AsyncTask. If you have any questions, please leave a message or go to the community of this site to communicate and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!