Android provides asynvtask in order to not block the main thread (UI thread), and UI updates can only be done in the main thread, so asynchronous processing is unavoidable.
Android in order to reduce the development difficulty, provided Asynctask.asynctask is a packaged background task class, is the asynchronous task.
Asynctask directly inherits from the object class, where the position is android.os.AsyncTask. To work with Asynctask we are going to provide three generic parameters and overload several methods (at least one for overloading).
Asynctask defines three types of generic type params,progress and result.
- The Params is the input parameter that initiates the task execution, such as the URL of the HTTP request.
- Progress the percentage of background task execution.
- Result background performs the final return of the task, such as String.
A minimum of one asynchronous loading of data is to override the following two methods:
- Doinbackground (Params ...) is performed in the background, and more time-consuming operations can be placed here. Note that it is not possible to manipulate the UI directly. This method is performed on a background thread, and it usually takes a long time to complete the task's main work. You can call Publicprogress (Progress ...) during execution. To update the progress of the task.
- OnPostExecute (Result) is equivalent to the way handler handles the UI, where it is possible to use the resulting processing action UI in Doinbackground. This method is executed on the main thread, and the result of the task execution is returned as a parameter to this method
You also have to rewrite these three methods, if necessary, but not necessarily:
- Onprogressupdate (Progress ...) You can use the progress bar to increase user experience. This method executes on the main thread and is used to show the progress of the task execution.
- OnPreExecute () Here is the interface when the end user calls Excute, and the progress dialog can be displayed here before the task executes before calling this method.
- Oncancelled () The action to be made when the user calls Cancel
Using the Asynctask class, here are a few guidelines to follow:
- The instance of the task 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 ...) These several methods;
- The task can only be executed once, otherwise the exception will occur when multiple calls are made;
Android Development--asynctask Detailed