AsyncTask, as its name implies, is used when we need to execute a synchronization task. This class can perform some background operations and then return the result to the UI, because this class encapsulates Handler and Thread, therefore, we do not need to directly operate these two classes, which is also very simple to use.
As mentioned in the source code, AsyncTask is suitable for some short operations (short operations). If you need to maintain multiple threads for a long time, we recommend using Executor, ThreadPoolExecutor, FutureTask, and other classes for implementation.
In fact, we usually use AsyncTask when downloading images and other small files.
When we use AsyncTask, We need to write a class to inherit AsyncTask (AsyncTask is an abstract class). We need to provide the generic type of three parameters (the most important three parameters of the AsyncTask class ):
- Parameters uploaded to the background before the execution of the Params task
- Progress of the background task execution in Progress.
- Result: The Result returned when the task is executed in the background.
When a synchronization task is executed, it takes four steps (can be understood as the lifecycle)
- OnPreExecute (), which will be executed before the synchronization task is executed (make some preparations, such as displaying a progress bar during download) (executed in the UI thread)
- DoInBackground, the most important and core work is carried out in this method. This method is executed in the background thread. In this method, you can call publishProgress () method To change the progress (this method is executed in the UI thread), of course, if you do not need to display the progress, you can also not use. DoInBackground finally requires that a result be returned, that is, the execution result.
- OnProgressUpdate: When publishProgress () is called, that is, when the progress changes, this method will be executed and executed in the UI thread. You can change the progress bar in this method. Of course, it is the same as publishProgress. If you do not need to display the progress, you do not need to use it.
- OnPostExecute, where you can use the result processing UI obtained in doInBackground. This method is executed in the main thread, and the task execution result is returned as a parameter of this method.
DownloadFilesTask count = totalSize = 0 ( i = 0; i < count; i+++=) ((i / () count) * 100 (isCancelled()) 0 "Downloaded " + result + " bytes"
We only need to create the class object in the UI thread, and then call its execute () method. If you want to cancel the AsyncTask task, run the cancel () method. If you want to cancel the task, you can override onCancelled (), this method will replace onPostExecute In the cancel task and be called back.