Asynctask is used in Android to download files and dynamically update the progress bar
1. Generics
AysncTask<Params,Progress,Result>
Params: the parameter passed in when starting the task, which is passed in by calling the asynctask. Execute (param) method.
Progress: the progress of background task execution. If the progress bar is not displayed, it does not need to be specified.
Result: the result returned at the end of the background task.
2. Important methods
Doinbackground (params... Params): the method that must be overridden. The background task is executed here and a new thread will be started. Params is the parameter passed in when starting the task. The number of parameters is variable.
OnPreExecute (): in the main thread, the operation before the background task is opened, such as displaying a progress bar dialog box.
OnPostExecute (Result result): when the background task is finished, it is called in the main thread to process the results returned by the doInBackground () method.
OnProgressUpdate (Progress... Values): when publishProgress (Progress... Values) is invoked in doInBackground (), it is called back to the main thread, and the number of parameters here is also uncertain.
Oncancelled(): cancels the task.
3. Precautions
(1) the execute () method must be invoked in the main thread.
(2) Asynctask instance must be created in the main thread;
(3) Do not manually call doinbackground(), onpreexecute(), onpostexecute(), onprogressupdate() methods;
(4) Pay attention to prevent memory leakage. Strong reference to activity in doinbackground () method may cause memory leakage.
4. Download File dynamic update progress bar (not encapsulated)
Layout:
Activity:
5. Download files and dynamically update the progress bar (encapsulation)
Activity:
DownloadHelper:
summary
The above is what Xiaobian introduced to you. In Android, asynctask is used to download files and dynamically update the progress bar. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!