Android asynchronous Processing

Source: Internet
Author: User

Original article to: http://www.pin5i.com/showtopic-android-asynctask-sample.html

Asynctask

It seems that the changed connect () method is available, but this method is anonymous.ThreadThere are defects: first, the thread overhead is large. If each task needs to create a thread, the applicationProgramSecond, the threads cannot be managed. After an anonymous thread is created and started, it is not controlled by the program. If many requests are sent, then a lot of threads will be started, and the system will be overwhelmed. In addition, we can see that the new thread is updated.UIHandler must also be introduced.CodeIt looks very bloated.

To solve this problem, ophone introduced asynctask in version 1.5. Asynctask is characterized by running tasks outside the main thread, and the callback method is executed in the main thread, which effectively avoids the trouble of using handler. According to the source code of asynctask, asynctask uses Java. util. concurrent.FrameworkConcurrent framework is a very mature and efficient framework for managing threads and task execution.Test. This shows that asynctask is designed to solve the problem of anonymous threads.

Asynctask is an abstract class. The subclass must implement the abstract method doinbackground (Params... P). In this method, the task is executed, such as connecting to the network to obtain data. Generally, the onpostexecute (result R) method should also be implemented, because the results that the application cares about are returned in this method. Note that asynctask must create instances in the main thread. Asynctask defines three generic types: Params, SS, and result.

* Input parameters for Params startup task execution, such as the URL of the HTTP request.
* Percentage of progress SS background tasks executed.
* Result: the result returned when a task is executed in the background, such as string.

Asynctask is executed in four steps, similar to the tasklistener defined earlier. Each step corresponds to a callback method. Note that these methods should not be called by the application. What developers need to do is to implement these methods. These methods are automatically called During task execution.

* Onpreexecute () This method is called before the task is executed. The progress dialog box is displayed here.
* Doinbackground (Params...) This method is executed in the background thread to complete the main work of the task, which usually takes a long time. During execution, you can call publicprogress (Progress...) to update the task progress.
* Onprogressupdate (Progress...) is executed in the main thread to display the task execution progress.
* Onpostexecute (result) This method is executed in the main thread, and the task execution result is returned as a parameter of this method.

Pagetask extends asynctask to read the webpage content in the doinbackground () method. PagetaskSource codeAs follows:

  1. // Set three types of parameters: String, integer, and string.
  2. Class pagetask extends asynctask <string, integer, string> {
  3.  
  4. // Variable length input parameter, which corresponds to asynctask. exucute ()
  5. @ Override
  6. Protected string doinbackground (string... Params ){
  7. Try {
  8. Httpclient client = new defaulthttpclient ();
  9. // Params [0] indicates the URL of the connection.
  10. Httpget = new httpget (Params [0]);
  11. Httpresponse response = client.exe cute (get );
  12. Httpentity entity = response. getentity ();
  13. Long length = entity. getcontentlength ();
  14. Inputstream is = entity. getcontent ();
  15. String S = NULL;
  16. If (is! = NULL ){
  17. Bytearrayoutputstream baos = new bytearrayoutputstream ();
  18. Byte [] Buf = new byte [1, 128];
  19. Int CH =-1;
  20. Int COUNT = 0;
  21. While (CH = is. Read (BUF ))! =-1 ){
  22. Baos. Write (BUF, 0, CH );
  23. Count + = CH;
  24. If (length> 0 ){
  25. // If you know the response length, call publishprogress () to update the progress.
  26. Publishprogress (INT) (count/(float) length) * 100 ));
  27. }
  28. // To clearly view the progress in the simulator, sleep the thread for 100 ms
  29. Thread. Sleep (100 );
  30. }
  31. S = new string (baos. tobytearray ());}
  32. // Return results
  33. Return S;
  34. } Catch (exception e ){
  35. E. printstacktrace ();
  36. }
  37. Return NULL;
  38. }
  39. @ Override
  40. Protected void oncancelled (){
  41. Super. oncancelled ();
  42. }
  43. @ Override
  44. Protected void onpostexecute (string result ){
  45. // Return the HTML page content
  46. Message. settext (result );
  47. }
  48. @ Override
  49. Protected void onpreexecute (){
  50. // Start the task. A dialog box is displayed here, which is simple.
  51. Message. settext (R. String. task_started );
  52. }
  53. @ Override
  54. Protected void onprogressupdate (integer... values ){
  55. // Update Progress
  56. Message. settext (Values [0]);
  57. }
  58. }

Copy code

Executing pagetask is very simple. You only need to call the following code. Re-run networkactivity to capture the webpage content and update the reading progress in real time. The reader tries to read a large web page to check the Update Progress of the percentage.

    1. Pagetask task = new pagetask ();
    2. Task.exe cute (URL. gettext (). tostring ());

Copy code

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.