AsyncTask realization of the principle, and apply the advantages and disadvantages

1) Principle AsyncTask implementation, and application advantages and disadvantages

AsyncTask, is lightweight asynchronous class android offers can be inherited directly AsyncTask, asynchronous operation in a class, and provides an interface feedback current level of executed asynchronously (via interface UI progress updates), Last feedback to the implementation of the main UI thread.

The advantage of using the:

l simple, fast

l controllable process

       

The disadvantage of using :

l in use and a plurality of asynchronous operations and the need for change Ui, it becomes complicated.

2) principle Handler asynchronous implementation and application of the advantages and disadvantages

Handler when the asynchronous implementation, involving Handler, Looper, Message, Thread four objects, the process is asynchronous main thread promoter Thread (sub-thread) àthread (sub-thread) runs and generates Message and Get Message-àLooper by-passed to HandleràHandler Looper get the Message, and UI changes.

The advantage of using the:

L clear structure and well-defined function

l For multiple background tasks, simple, clear

   

The disadvantage of using:

l when a single background asynchronous processing, the code appears too large, too complex structure (relative)

 
Introduction AsyncTask
Android's Handler AsyncTask more lightweight than some for simple asynchronous processing.
First, there is a clear reason why Android Handler and AsyncTask, all in order not to block the main thread (UI thread), and update the UI can only be done in the main thread, asynchronous processing is therefore inevitable.
 

Android To reduce the development effort and provides AsyncTask. AsyncTask is a package over background tasks like the name suggests is asynchronous tasks.

AsyncTask directly inherited from the Object class, location android.os.AsyncTask. To use AsyncTask work we have to provide three generic parameters, and override a few methods (at least a heavy load).

 

AsyncTask defines three generic types Params, Progress and Result.

  • Params start input parameters of task execution, such as the HTTP request URL.
  • Percentage Progress background tasks to perform.
  • The results Result eventual return of the background tasks, such as String.

Used AsyncTask students know an asynchronous load data to be rewritten at least two of the following methods:

  • doInBackground (Params ...) background, time-consuming operation can be placed here. Note that there can not be directly manipulated UI. This method of execution in a background thread to complete the task of major work, usually takes a long time. In the process of implementation can call publicProgress (Progress ...) to update the progress of the task.
  • onPostExecute (Result) corresponding to the UI processing Handler manner, there can be used the results obtained doInBackground UI processing operation. This method of execution in the main thread, the results of tasks performed as a parameter of this method returns

If necessary you have to rewrite all three of the following methods, but not necessary:

  • onProgressUpdate (Progress ...) You can use the progress bar to increase the user experience. This method of execution in the main thread, the progress display for task execution.
  • onPreExecute () Here is the interface when the end-user invokes Excute, when before task execution start calling this method, you can display a progress dialog here.
  • onCancelled () when the user calls to cancel, do the operation

Use AsyncTask class, here are a few guidelines that must be followed:

  • Examples Task must be created in the UI thread;
  • execute method must be called in the UI thread;
  • Do not manually call onPreExecute (), onPostExecute (Result), doInBackground (Params ...), onProgressUpdate (Progress ...) these methods;
  • This task can only be executed once, otherwise there will be an exception when called multiple times;

A super-simple to understand examples of 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 = "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. // simulated network environment  
  5. public class NetOperator {  
  6.       
  7.     public void operator(){  
  8.         try {  
  9.             // Sleep 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 an object class, and call the execute method  
  8.  * OnProExecute method is performed first  
  9.  * Second execution method doInBackgroup  
  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.      Integer * here corresponds to the first parameter in the argument AsyncTask   
  27.      * String corresponding to the return value of this third parameter AsyncTask  
  28.      * This method does not run in the UI thread which is mainly used for asynchronous operation, all spaces can not be provided among the UI and modifications in the method  
  29.      * However, the method can be called publishProgress trigger onProgressUpdate the UI operation  
  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.      * String parameter corresponding to herein AsyncTask the third parameter (i.e. doInBackground received return value)  
  45.      * In the run after the execution doInBackground method, and can be set to run on the UI thread among UI space  
  46.      */  
  47.     @Override  
  48.     protected void onPostExecute(String result) {  
  49.         textView.setText ( "asynchronous operation execution finished" + result);  
  50.     }  
  51.   
  52.   
  53.     // This method runs in the UI thread them, and can be set to run on the UI thread among UI space  
  54.     @Override  
  55.     protected void onPreExecute() {  
  56.         textView.setText ( "begin to perform asynchronous thread");  
  57.     }  
  58.   
  59.   
  60.     /**  
  61.      * Here Intege parameter corresponds to the second parameter AsyncTask  
  62.      * DoInBackground method in which each call publishProgress ,, methods will trigger execution onProgressUpdate  
  63.      * OnProgressUpdate is executed in the UI thread, and all can be manipulated 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

Guess you like

Origin blog.csdn.net/weixin_33810006/article/details/92033270