The Principle of AsyncTask Implementation and the Advantages and Disadvantages of Its Application

Posted by nade93 on Fri, 14 Jun 2019 21:08:46 +0200

1) Principles of AsyncTask implementation, advantages and disadvantages of its application

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

Advantages of use:

l. Simple and fast

l. Process controllability

       

Disadvantages of use:

l. When multiple asynchronous operations are used and Ui changes are required, they become complex.

2) Principles and advantages and disadvantages of Handler asynchronous implementation

In Handler asynchronous implementation, it involves four objects: Handler, Looper, Message and Thread. The process of asynchronous implementation is that the main thread starts Thread (sub-thread) thread running and generates Message-Looper to get the message and pass it to Handler Handler to get the message in Looper one by one, and make UI changes.

Advantages of use:

l. Clear structure and clear functional definition

l. Simple and clear for multiple background tasks

   

Disadvantages of use:

l. When dealing with single background asynchronously, it appears that there is too much code and too complex structure (relativity)

 
Introduction to AsyncTask
Android's syncTask is lighter than Handler's and is suitable for simple asynchronous processing.
First of all, it is clear that Android has Handler and syncTask in order not to block the main thread (UI thread), and UI updates can only be completed in the main thread, so asynchronous processing is inevitable.
 

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

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

 

AsyncTask defines three generic types Params, Progress and Result.

  • Params starts the input parameters for task execution, such as the URL of the HTTP request.
  • Percentage of background task execution for Progress.
  • Result background execution tasks eventually return results, such as String.

Students who have used AsyncTask know that an asynchronous loading data must at least rewrite the following two methods:

  • doInBackground(Params... ) Background execution, more time-consuming operations can be placed here. Note that the UI cannot be manipulated directly here. It usually takes a long time for this method to execute in the background thread and complete the main task. You can call publicProgress during execution. ) To update the progress of the task.
  • onPostExecute(Result) is equivalent to the way Handler processes the UI, where the result obtained in doInBackground can be used to process the operation UI. 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 not necessarily:

  • OnProgress Update ) You can use progress bars to increase user experience. This method is executed in the main thread to show the progress of task execution.
  • onPreExecute() This is the interface where the end user calls Excute. This method is called before the task is executed, and the progress dialog box can be displayed here.
  • onCancelled() The action to be done when the user calls cancel

Using the AsyncTask class, the following guidelines must be followed:

  • Task instances must be created in UI thread s;
  • The execute method must be called in the UI thread.
  • Do not manually call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...).
  • This task can only be executed once, otherwise it will be abnormal when it is called many times.

An ultra-simple example of understanding AsyncTask:

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7.     <TextView    
  8.     android:id="@+id/textView01"  
  9.     android:layout_width="fill_parent"   
  10.     android:layout_height="wrap_content"   
  11.     />  
  12.    <ProgressBar   
  13.    android:id="@+id/progressBar02"  
  14.     android:layout_width="fill_parent"   
  15.     android:layout_height="wrap_content"   
  16.     style="?android:attr/progressBarStyleHorizontal"   
  17.     />  
  18.     <Button  
  19.     android:id="@+id/button03"  
  20.     android:layout_width="fill_parent"   
  21.     android:layout_height="wrap_content"   
  22.     android:text="To update progressbar"  
  23.     />  
  24. </LinearLayout>  


MainActivity.java

  1. package vic.wong.main;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.widget.Button;  
  8. import android.widget.ProgressBar;  
  9. import android.widget.TextView;  
  10.   
  11. public class MainActivity extends Activity {  
  12.     private Button button;  
  13.     private ProgressBar progressBar;  
  14.     private TextView textView;  
  15.       
  16.     @Override  
  17.     public void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.main);  
  20.           
  21.         button = (Button)findViewById(R.id.button03);  
  22.         progressBar = (ProgressBar)findViewById(R.id.progressBar02);  
  23.         textView = (TextView)findViewById(R.id.textView01);  
  24.           
  25.         button.setOnClickListener(new OnClickListener() {  
  26.               
  27.             @Override  
  28.             public void onClick(View v) {  
  29.                 ProgressBarAsyncTask asyncTask = new ProgressBarAsyncTask(textView, progressBar);  
  30.                 asyncTask.execute(1000);  
  31.             }  
  32.         });  
  33.     }  
  34. }  

 


NetOperator.java

  1. package vic.wong.main;  
  2.   
  3.   
  4. //Analog network environment
  5. public class NetOperator {  
  6.       
  7.     public void operator(){  
  8.         try {  
  9.             //Sleep for 1 second.
  10.             Thread.sleep(1000);  
  11.         } catch (InterruptedException e) {  
  12.             // TODO Auto-generated catch block  
  13.             e.printStackTrace();  
  14.         }  
  15.     }  
  16.   
  17. }  

 


ProgressBarAsyncTask .java 

  1. package vic.wong.main;  
  2. import android.os.AsyncTask;  
  3. import android.widget.ProgressBar;  
  4. import android.widget.TextView;  
  5.   
  6. /**  
  7.  * After generating the object of this class and calling the execute method,
  8.  * The onProExecute method is executed first.
  9.  * Next, execute the doInBackgroup method.
  10.  *  
  11.  */  
  12. public class ProgressBarAsyncTask extends AsyncTask<Integer, Integer, String> {  
  13.   
  14.     private TextView textView;  
  15.     private ProgressBar progressBar;  
  16.       
  17.       
  18.     public ProgressBarAsyncTask(TextView textView, ProgressBar progressBar) {  
  19.         super();  
  20.         this.textView = textView;  
  21.         this.progressBar = progressBar;  
  22.     }  
  23.   
  24.   
  25.     /**  
  26.      * The Integer parameter here corresponds to the first parameter in AsyncTask.
  27.      * The String return value here corresponds to the third parameter of AsyncTask.
  28.      * This method does not run in UI threads and is mainly used for asynchronous operation. All the spaces in UI can not be set and modified in this method.
  29.      * But you can call the publishProgress method to trigger onProgressUpdate to operate on the UI.
  30.      */  
  31.     @Override  
  32.     protected String doInBackground(Integer... params) {  
  33.         NetOperator netOperator = new NetOperator();  
  34.         int i = 0;  
  35.         for (i = 10; i <= 100; i+=10) {  
  36.             netOperator.operator();  
  37.             publishProgress(i);  
  38.         }  
  39.         return i + params[0].intValue() + "";  
  40.     }  
  41.   
  42.   
  43.     /**  
  44.      * The String parameter here corresponds to the third parameter in AsyncTask (that is, to receive the return value of doInBackground)
  45.      * Running after the execution of the doInBackground method and running in the UI thread can set the UI space.
  46.      */  
  47.     @Override  
  48.     protected void onPostExecute(String result) {  
  49.         textView.setText("End of asynchronous operation execution" + result);  
  50.     }  
  51.   
  52.   
  53.     //This method runs in the UI thread and in the UI thread. It can set the UI space.
  54.     @Override  
  55.     protected void onPreExecute() {  
  56.         textView.setText("Start executing asynchronous threads");  
  57.     }  
  58.   
  59.   
  60.     /**  
  61.      * The Intege parameter here corresponds to the second parameter in AsyncTask.
  62.      * In the doInBackground method, each call to the publishProgress method triggers onProgressUpdate execution.
  63.      * onProgressUpdate Is executed in UI threads, all of which can operate on UI space.
  64.      */  
  65.     @Override  
  66.     protected void onProgressUpdate(Integer... values) {  
  67.         int vlaue = values[0];  
  68.         progressBar.setProgress(vlaue);  
  69.     }  
  70.   
  71.       
  72.       
  73.       
  74.   

Reproduced in: https://my.oschina.net/yourpapa/blog/621603

Topics: Android Java xml Python