Asynchronous tasks are provided in order to modify the UI component in a new thread , but we can also use Handler to implement communication between threads in order to solve this problem. But asynchronous tasks provide us with a way to further simplify.
The steps for using Asynctask are as follows:
1. Create a subclass of Asynctask in the UI thread (which must be created in the UI thread), specifying three generic parameters: the one you don't need can be specified as Void
Params: The type of input parameter that initiates the task execution.
Progress: The type of progress value that the background task completed.
Result: The type of the result returned when the background task completes.
2. The following methods are implemented for Asynctask (These are all called by the Android system and do not need to be called by the programmer):
Doinbackground (params ... params): A task that a background thread needs to complete. executes after the OnPreExecute. This method receives the input parameter and returns the result of the calculation. You can call publishprogress (Progress. Values) during execution to update the progress information.
Onprogressupdate (Progress. Values): This method is executed whencalling publishprogress (Progress ... values) , Updates the progress information directly to the UI component.
OnPreExecute (): Called before performing a task on a background thread. Typically used to complete some initialization operations.
OnPostExecute (Result result): Called after the task of the background thread is executed. executes after the doinbackground.
3. Call the Execute () method of the Asynctask subclass to begin performing background tasks. (must be called in the UI thread)
It is important to note that Asynctask can only be called once, and multiple calls will throw an exception.
Android Learning Note (39): Asynchronous Task Asynctask