Asynctask solves Android UI congestion problems

Source: Internet
Author: User
Asynctask solves the android UI congestion problem. We usually develop android Program In case of processing time-consuming tasks, such as database operations accessed by I/O, network access, and other issues, the UI is suspended. This problem can be solved through asynctask, today, we will execute downloader in Android. downloadfile (URL) may block the entire interface. Obviously, this will affect the user experience. How can we solve this problem? Method 1,
Create a new thread to execute our task. Use the Thread class to write the task in run () {}. Code For example, check

Print?01.New Thread (New Runnable (){02. 03.Public Void Run (){04. 05. Downloader. downloadfile (URL );06. 07.}08. 09.}). Start ();

However, using the thread will produce some unexpected problems, and the programmer needs to manually maintain it with more code.
Method 2: The android SDK provides a backend task processing tool asynctask. Asynctask is an encapsulated background task class. as its name implies, it is an asynchronous task to facilitate our maintenance. The Android Development Network prompts that this benefit can solve some thread security problems. asynctask directly inherits from the object class, the location is Android. OS. asynctask. To use asynctask, we need to provide three generic parameters and reload four methods (at least one ).
Three generic types:
Param, the data type required by the task executor
Progress unit data type used in background computing of progress
Data Type of the result returned by the result background computing
Some parameters can be set to not used, as long as they are passed to the void type, such as asynctask
Four steps:
Onpreexecute () is used to execute preprocessing. It runs in the UI thread and can be used to prepare background tasks, such as drawing a progress bar control.
Doinbackground (Params...), the specific calculation of background process execution is implemented here, doinbackground (Params...) is the key of asynctask, and this method must be reloaded. In this method, you can use publishprogress (Progress...) to change the current progress value.
Onprogressupdate (Progress...), run on the UI thread. If publishprogress (Progress...) is used in doinbackground (Params...), this method is triggered. Here, you can make a specific response to the progress bar Control Based on the Progress value.
Onpostexecute (result), which runs on the UI thread and can process the results of background tasks. The result is the return value of doinbackground (Params. This method should also be reloaded frequently. If the result is null, the background task is not completed (canceled or abnormal ).
Asynctask instance code: Check

Print? 01. Private Class DownloadfilestaskExtends Asynctask { 02. 03. Protected Long doinbackground (URL... URLs ){ 04. 05. Int Count = URLs. length; 06. 07. Long Totalsize =0; 08. 09. For (Int I =0; I <count; I ++ ){ 10. 11. Totalsize + = Downloader. downloadfile (URLs [I]); 12. 13. Publishprogress ((Int) (I /(Float) Count )*100));// Download progress Calculation 14. 15. } 16. 17. Return Totalsize; 18. 19. } 20. 21. Protected Void Onprogressupdate (integer... progress ){ 22. 23. Setprogresspercent (Progress [0]);// Update Progress display 24. 25. } 26. 27. Protected Void Onpostexecute (long result ){ 28. 29. Showdialog ("Android123 download test" + Result +"Bytes"); 30. 31. } 32. 33. } 34. 35. In activity, we use it like this: 36. 37. Try{ 38. 39. New Downloadfilestask (cmd.exe cute (URL ); 40. 41. }Catch (Exception e ){ 42. 43. Log. E ("Error", E. tostring ()); 44. 45. }

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.