AsyncTask is a very commonly used API, especially when processing data asynchronously and applying data to views. In fact, AsyncTask is not that good, and it is even a bit bad. In this article, I will talk about what problems AsyncTask will cause, how to fix these problems, and some alternatives to AsyncTask.
AsyncTask
Starting with Android API 3 (1.5 Cupcake), AsyncTask has been introduced to help developers manage threads more easily. In fact, there are similar implementations in Android 1.0 and 1.1, that is UserTask. UserTask and AsyncTask have the same API and implementation, but since the slightest share of 1.0 and 1.1, the concept here will not involve UserTask.
life cycle
There is such a widespread misunderstanding about AsyncTask, and many people believe that an AsyncTask in Activity will be destroyed as the Activity is destroyed. Then that's not the case. AsyncTask will execute the doInBackground() method until the method execution ends. Once the above method is completed, different operations will be performed according to the situation.
If cancel(boolean) is called, the onCancelled(Result) method is executed
If cancel(boolean) is not called, execute the onPostExecute(Result) method
The cancel method of AsyncTask requires a Boolean parameter named mayInterruptIfRunning, which means whether it can be interrupted if it is being executed. If this value is set to true, it means that the task can be interrupted. Otherwise, the executing program will continue to be executed until it is completed. If there is a loop operation in the doInBackground() method, we should use isCancelled() in the loop to judge. If it returns true, we should avoid performing subsequent useless loop operations.
In short, we need to make sure that AsyncTask is cancelled correctly.
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
Controllable process
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 The percentage of execution of background tasks.
•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 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() Here 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() The action to be done when the user calls cancel
Using the AsyncTask class, the following are several guidelines that must be followed:
•Task instances 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="." encoding="utf-"?> <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(); progressBar = (ProgressBar)findViewById(); textView = (TextView)findViewById(); (new OnClickListener() { @Override public void onClick(View v) { ProgressBarAsyncTask asyncTask = new ProgressBarAsyncTask(textView, progressBar); (); } }); } }
package ; //Simulate network environmentpublic class NetOperator { public void operator(){ try { //Sleep seconds(); } 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 = ; for (i = ; i <= ; i+=) { (); publishProgress(i); } return i + params[].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[]; (vlaue); } }
That’s all for you about AsyncTask in Android, I hope it will be helpful to you!