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)
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
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:id="@+id/textView01"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <ProgressBar
- android:id="@+id/progressBar02"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- style="?android:attr/progressBarStyleHorizontal"
- />
- <Button
- android:id="@+id/button03"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- Android: text = "Update progressbar"
- />
- </LinearLayout>
MainActivity.java
- package vic.wong.main;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ProgressBar;
- import android.widget.TextView;
- public class MainActivity extends Activity {
- private Button button;
- private ProgressBar progressBar;
- private TextView textView;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- button = (Button)findViewById(R.id.button03);
- progressBar = (ProgressBar)findViewById(R.id.progressBar02);
- textView = (TextView)findViewById(R.id.textView01);
- button.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- ProgressBarAsyncTask asyncTask = new ProgressBarAsyncTask(textView, progressBar);
- asyncTask.execute(1000);
- }
- });
- }
- }
NetOperator.java
- package vic.wong.main;
- // simulated network environment
- public class NetOperator {
- public void operator(){
- try {
- // Sleep 1 second
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace ();
- }
- }
- }
ProgressBarAsyncTask .java
- package vic.wong.main;
- import android.os.AsyncTask;
- import android.widget.ProgressBar;
- import android.widget.TextView;
- /**
- * After generating an object class, and call the execute method
- * OnProExecute method is performed first
- * Second execution method doInBackgroup
- *
- */
- public class ProgressBarAsyncTask extends AsyncTask<Integer, Integer, String> {
- private TextView textView;
- private ProgressBar progressBar;
- public ProgressBarAsyncTask(TextView textView, ProgressBar progressBar) {
- super();
- this.textView = textView;
- this.progressBar = progressBar;
- }
- /**
- Integer * here corresponds to the first parameter in the argument AsyncTask
- * String corresponding to the return value of this third parameter AsyncTask
- * 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
- * However, the method can be called publishProgress trigger onProgressUpdate the UI operation
- */
- @Override
- protected String doInBackground(Integer... params) {
- NetOperator netOperator = new NetOperator ();
- int i = 0;
- for (i = 10; i <= 100; i+=10) {
- netOperator.operator();
- publishProgress(i);
- }
- return i + params[0].intValue() + "";
- }
- /**
- * String parameter corresponding to herein AsyncTask the third parameter (i.e. doInBackground received return value)
- * In the run after the execution doInBackground method, and can be set to run on the UI thread among UI space
- */
- @Override
- protected void onPostExecute(String result) {
- textView.setText ( "asynchronous operation execution finished" + result);
- }
- // This method runs in the UI thread them, and can be set to run on the UI thread among UI space
- @Override
- protected void onPreExecute() {
- textView.setText ( "begin to perform asynchronous thread");
- }
- /**
- * Here Intege parameter corresponds to the second parameter AsyncTask
- * DoInBackground method in which each call publishProgress ,, methods will trigger execution onProgressUpdate
- * OnProgressUpdate is executed in the UI thread, and all can be manipulated UI space
- */
- @Override
- protected void onProgressUpdate(Integer... values) {
- int vlaue = values[0];
- progressBar.setProgress(vlaue);
- }
- }
Reproduced in: https: //my.oschina.net/yourpapa/blog/621603