Detail AsyncTask mechanism in Android

  • 2020-12-07 04:23:58
  • OfStack

In Android, there are two ways to solve the problem of direct communication between threads, one through THE Handler mechanism and the other through the AsyncTask mechanism, which I will explain in detail today.

AsyncTask

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

How do you understand AsyncTask? In layman's terms, AsyncTask is equivalent to Android, which provides us with a framework for multithreaded programming. It is between Thread and Handler. If we want to define an AsyncTask, we need to define a class to inherit from AsyncTask and implement the only abstract doInBackgroud method.

Three generic parameters:

AsyncTask < Params, Progress, Result >

The & # 8226; Params: Input parameter to start task execution, such as URL requested by HTTP.
The & # 8226; Progress: Percentage of desk tasks executed.
The & # 8226; Result: The final result of a task performed in the background, such as String.

If neither is specified, write it as Void, for example:

AsyncTask < Void, Void, Void > The & # 8226; onPreExecute(): This method is executed before performing asynchronous tasks and is performed in UI Thread, where we usually do some initialization of UI controls, such as eject to ProgressDialog

The & # 8226; doInBackground(Params... params) : in onPreExecute () method is performed after, will immediately execute this method, this method is the way to handle the asynchronous task, Android operating system in the background of the thread pool open 1 worker thread to perform our this method, so this method is in worker thread execution, this method performs after our execution results can be sent to us last 1 onPostExecute method, in this way, we can get the data from the network, such as more time-consuming operation

The & # 8226; onProgressUpdate(Progess... values): This method is also implemented in UI Thread. When asynchronous tasks are executed, we sometimes need to return the progress of execution to our UI interface. For example, when downloading a network picture, we need to display the progress of its download all the time, so we can use this method to update our progress. Before calling this method, we need to call an publishProgress(Progress) method in the doInBackground method to pass our progress to the onProgressUpdate method every second to update it

The & # 8226; onPostExecute(Result... result): When our asynchronous task completes, we return the result to this method, which was also called in UI Thread, and we can display the result on the UI control
The & # 8226; onCancelled() : What to do when the user invokes cancellation

code


public class yibu extends AsyncTask<Integer, Integer, String> {
 private int num = 0;
 private TextView text;
 public yibu(TextView textfrom) {
  // TODO  Automatically generated constructor stubs 
  this.text = textfrom;// Passed in 1 a TextView
 }
 @Override
 protected void onPostExecute(String result) {
  // TODO  Automatically generated method stubs 
  super.onPostExecute(result);
  text.setText(" The asynchronous operation finishes " + result);
 }
 @Override
 protected void onPreExecute() {
  // TODO  Automatically generated method stubs 
  super.onPreExecute();
  text.setText(" Start performing the asynchronous operation ");
 }
 @Override
 protected void onProgressUpdate(Integer... values) {
  // TODO  Automatically generated method stubs 
  super.onProgressUpdate(values);
  int value = values[0];
  System.out.println(value);
 }
 @Override
 protected String doInBackground(Integer... param) {
  // TODO  Automatically generated method stubs  
  for(;num<10;num++)
  {
   publishProgress(num);// call onProgressUpdate()
  }
  return num + param[0].intValue() + "";// call onPostExecute I'm just going to pass it in 
 }
}

PS: Comparison between AsyncTask and Handler

1) The principle of AsyncTask implementation, as well as its applicable advantages and disadvantages

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

Advantages of use:

Easy and fast

Process control

Disadvantages of use:

This becomes complicated when multiple asynchronous operations are used and Ui changes are required.

2) The principle of Handler asynchronous implementation and its applicable advantages and disadvantages

The asynchronous implementation of Handler involves four objects, Handler, Looper, Message and Thread.the asynchronous implementation process is that the main thread starts Thread (child thread) athread (child thread) to run and generates ES146en-AES147en to get Message and pass it to HandleraHandler to get Message in Looper one by one and make UI changes.

Advantages of use:

Clear structure and clear function definition

Simple and clear for multiple background tasks

Disadvantages of use:

In a single background asynchronous processing, appears too much code, structure is too complex (relativity)


Related articles: