An overview,

AsyncTask is a lightweight asynchronous task class that belongs to an abstract class and requires subclasses and related methods. It can perform background tasks in the thread pool, and then transfer the execution progress and final results to the main thread and update THE UI in the main thread. Through AsyncTask, it is more convenient to perform background tasks and operate UI in the main thread, which can easily solve the communication problem between multiple threads. However, AsyncTask is not suitable for very time-consuming background tasks. For very time-consuming tasks, thread pools are recommended.

Second, the role of

  1. Implement multithreading: Perform tasks in worker threads, such as time-consuming tasks.

  2. Asynchronous communication and message passing: realize the communication between worker thread and main thread (UI thread), that is, transfer the execution result of worker thread to main thread, so that relevant UI operations can be performed in the main thread, and finally ensure thread safety.

Three advantages,

  1. Facilitate asynchronous communication: no complex combination of “task threads (such as inheriting Thread classes) + Handler” is required.

  2. Save resources: the use of thread pool cache thread + reuse thread, avoid frequent creation & destruction of threads brought by the system resource overhead.

Core methods

To master AsyncTask, you need to master three parameters and four steps.

1. Three parameters

AsyncTask<Params, Progress, Result>
Copy the code

Params: Indicates the type of argument that is passed to the doInBackground() method of AysncTask when the asynchronous task is executed

Progress: Parameter type that represents the Progress of an asynchronous task and is used as an argument to the onProgressUpdate() method

Result: Parameter type of the Result returned by the asynchronous task, which is used as an argument to the onPostExecute() method

When defining a class that inherits AsyncTask, we must specify the types of all three generics. If none is specified, Void is used, for example:

AsyncTask <Void, Void, Void>
Copy the code

2. Four steps

When executing an asynchronous task, follow the following four steps:

OnPreExecute () : This method is executed before the asynchronous task is executed, and is executed in the UI Thread. Normally, we do some initialization of the UI control in this method, such as popping ProgressDialog.

doInBackground(Params… Params) : The onPreExecute() method is executed immediately after the onPreExecute() method is executed. This method is a method that handles asynchronous tasks. The Android operating system starts a worker thread in the background thread pool to execute this method. After execution, the result is sent to the final onPostExecute method, which can fetch data from the network and other time-consuming operations.

onProgressUpdate(Progess… Values) : This method is also implemented in UIThread. During the execution of asynchronous tasks, sometimes the progress of the execution needs to be returned to the UI interface. For example, when downloading a network image, we need to display the progress at any time, so we can use this method to update the progress. Before calling this method, we need to call a publishProgress(Progress) method in the doInBackground method to pass the Progress to the onProgressUpdate method for updating.

onPostExecute(Result… Result: When the asynchronous task completes, the result is returned to this method, which is also called in the UI Thread. We can display the returned result on the UI control.

3. Supplement doInBackground and onCancelled

(1) Why does the AsyncTask abstract class only have a doInBackground abstract method?

If we were to do an asynchronous task, we would have to create a new Thread for the ProgressDialog to complete some operations, which might not require popping up the ProgressDialog, updating the ProgressDialog’s progress bar, or updating the results to the UI. So none of the three methods, other than the doInBackground method, are required, so the method that you have to implement is the doInBackground method.

(2) Cancel a Task- Cancel an asynchronous Task

Cancelled() callback. The asynchronous task can be cancelled at any time by calling the cancel(Boolean) method, which will then be called isCancelled() and return true. If this method is called, onPostExecute() will not be called after the doInBackgroud() method completes, but onCancelled() will be called instead. To ensure that the Task has been cancelled, isCancelled() is often called, if necessary.

Five, basic use

The steps of using AsyncTask are divided into two steps:

  • Step 1: Create AsyncTask subclasses & implement core methods as required
  • Step 2: Create an instance object of the AsyncTask subclass and manually call execute() to execute the asynchronous thread task
Class AsyncTask; class AsyncTask; class AsyncTask; If not, use java.lang.Void instead. Private Class MyTask extends AsyncTask<Params, Progress, Result> {// Action before executing thread task @override protected voidonPreExecute() {... } // Receive input arguments, perform time-consuming operations in the task, and return the result of thread task execution @override protected StringdoInBackground(String... Params) {// Custom thread task HttpClient HttpClient = new DefaultHttpClient(); . // publishProgress() is called to show progress, after which onProgressUpdate() publishProgress(count) is called; Override protected void onProgressUpdate(Integer... progresses) { ... @override protected void onPostExecute(String result) {// UI operation..... } // Set the asynchronous task to: Override protected voidonCancelled() {... }}Copy the code
Step 2: Create an instance object of the AsyncTask subclass and manually call execute(Params... MyTask mTask = new MyTask(); mTask.execute();Copy the code

Six, when using matters needing attention

1. Principles for using AsyncTask

(1) Instances of AsyncTask subclasses must be created in the UI thread

(2) The execute method must be called in the UI thread

(3) The same AsyncTask instance object can only be executed once. If it is executed twice, an exception will be thrown

(4) During the execution of the task, the system will automatically call a series of AsyncTask methods: onPreExecute(), doInBackground(), onProgressUpdate() and onPostExecute(). These methods cannot be called manually

2. Memory leakage caused by AsyncTask

Cause: The Activity cannot be released because a non-static inner class holds an anonymous reference to an external class

Solution: AsyncTask holds a weak reference to an external Activity inside. AsyncTask is replaced with a static inner class. Asynctask.cancel () is cancelled before the Activity is destroyed to ensure stability

Seven,

This article describes the basic usage of AysncTask and the considerations for using it, including compliance and memory leaks. Later, we will analyze how AysncTask works, including whether AysncTask is serial or parallel when multitasking and source code analysis.