Android self-use -- asynctask implements asynchronous Processing Tasks

Source: Internet
Author: User
When developing Android applications, you must follow the single-thread model principle: Android UI operations are not thread-safe and must be executed in the UI thread. In a single-threaded model, you must always remember the following two rules:
1. Do not block the UI thread
2. Make sure to only access the android UI toolkit in the UI thread
When a program is started for the first time, Android starts a corresponding main thread at the same time. The main thread is mainly responsible for processing UI-related events, such as user key events, the user contacts screen events and Screen Drawing events, and distributes related events to corresponding components for processing. Therefore, the main thread is often called the UI thread.
For example, you can obtain a webpage from the Internet and display its source code in a textview. This kind of program involving network operations generally requires a thread to complete network access. However, after obtaining the page source code, yes. textview cannot be called directly in the Network Operation thread. settext. because other threads cannot directly access the main UI thread Member

Android provides several methods to access the UI thread in other threads.
Activity. runonuithread (runnable)
View. Post (runnable)
View. postdelayed (runnable, long)
Hanlder
These classes or methods also make your code complex and hard to understand. However, when you need to implement complex operations and frequently update the UI, this will become worse.

To solve this problem, Android 1.5 provides a tool class: asynctask, which makes it easier to create long-running tasks that need to interact with the user interface. It can be implemented without using threads and handler.
Asynctask is an abstract class. 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 background tasks.
Result: The result returned when the task is executed in the background, such as string.

The execution of asynctask is divided into four steps. Each step corresponds to a callback method, which should not be called by the application. All developers need to do is implement these methods.
1) subclass asynctask
2) implement one or more of the following methods defined in asynctask
Onpreexecute (), this method will be called by the UI thread before the actual background operation is executed. You can make some preparations in this method, such as displaying a progress bar on the interface.
Doinbackground (Params...) will be executed immediately after the onpreexecute method is executed. This method runs in the background thread. Here, we will primarily perform those time-consuming background computing tasks. You can call publishprogress to update the real-time task progress. This method is an abstract method and must be implemented by sub-classes.
Onprogressupdate (Progress...), after the publishprogress method is called, UI thread will call this method to display the progress of the task on the interface, for example, display through a progress bar.
Onpostexecute (result). After doinbackground is executed, the onpostexecute method will be called by the UI thread, and the background computing result will be passed to the UI thread through this method.

To correctly use the asynctask class, the following guidelines must be followed:
1) The task instance must be created in the UI thread.
2) The execute method must be called in the UI thread.
3) do not manually call the onpreexecute (), onpostexecute (result), doinbackground (Params...), onprogressupdate (Progress...) methods.
4) The task can only be executed once. Otherwise, exceptions may occur during multiple calls.

Obtain a webpage from the Internet and display its source code in a textview.

Java code
  1. Package test. List;
  2. Import java. Io. bytearrayoutputstream;
  3. Import java. Io. inputstream;
  4. Import java. util. arraylist;
  5. Import org. Apache. http. httpentity;
  6. Import org. Apache. http. httpresponse;
  7. Import org. Apache. http. Client. httpclient;
  8. Import org. Apache. http. Client. Methods. httpget;
  9. Import org. Apache. http. impl. Client. defaulthttpclient;
  10. Import Android. App. activity;
  11. Import Android. App. progressdialog;
  12. Import Android. content. context;
  13. Import Android. content. dialoginterface;
  14. Import Android. OS. asynctask;
  15. Import Android. OS. Bundle;
  16. Import Android. OS. Handler;
  17. Import Android. OS. message;
  18. Import Android. View. view;
  19. Import Android. widget. Button;
  20. Import Android. widget. edittext;
  21. Import Android. widget. textview;
  22. Public class networkactivity extends activity {
  23. Private textview message;
  24. Private button open;
  25. Private edittext URL;
  26. @ Override
  27. Public void oncreate (bundle savedinstancestate ){
  28. Super. oncreate (savedinstancestate );
  29. Setcontentview (R. layout. Network );
  30. Message = (textview) findviewbyid (R. Id. Message );
  31. Url = (edittext) findviewbyid (R. Id. url );
  32. Open = (button) findviewbyid (R. Id. Open );
  33. Open. setonclicklistener (New View. onclicklistener (){
  34. Public void onclick (view arg0 ){
  35. Connect ();
  36. }
  37. });
  38. }
  39. Private void connect (){
  40. Pagetask task = new pagetask (this );
  41. Task.exe cute (URL. gettext (). tostring ());
  42. }
  43. Class pagetask extends asynctask <string, integer, string> {
  44. // Variable length input parameter, which corresponds to asynctask. exucute ()
  45. Progressdialog pdialog;
  46. Public pagetask (context ){
  47. Pdialog = new progressdialog (context, 0 );
  48. Pdialog. setbutton ("cancel", new dialoginterface. onclicklistener (){
  49. Public void onclick (dialoginterface dialog, int I ){
  50. Dialog. Cancel ();
  51. }
  52. });
  53. Pdialog. setoncancellistener (New dialoginterface. oncancellistener (){
  54. Public void oncancel (dialoginterface DIALOG ){
  55. Finish ();
  56. }
  57. });
  58. Pdialog. setcancelable (true );
  59. Pdialog. setmax (100 );
  60. Pdialog. setprogressstyle (progressdialog. style_horizontal );
  61. Pdialog. Show ();
  62. }
  63. @ Override
  64. Protected string doinbackground (string... Params ){
  65. Try {
  66. Httpclient client = new defaulthttpclient ();
  67. // Params [0] indicates the URL of the connection.
  68. Httpget = new httpget (Params [0]);
  69. Httpresponse response = client.exe cute (get );
  70. Httpentity entity = response. getentity ();
  71. Long length = entity. getcontentlength ();
  72. Inputstream is = entity. getcontent ();
  73. String S = NULL;
  74. If (is! = NULL ){
  75. Bytearrayoutputstream baos = new bytearrayoutputstream ();
  76. Byte [] Buf = new byte [1, 128];
  77. Int CH =-1;
  78. Int COUNT = 0;
  79. While (CH = is. Read (BUF ))! =-1 ){
  80. Baos. Write (BUF, 0, CH );
  81. Count + = CH;
  82. If (length> 0 ){
  83. // If you know the response length, call publishprogress () to update the progress.
  84. Publishprogress (INT) (count/(float) length) * 100 ));
  85. }
  86. // Sleep the thread for 100 ms
  87. Thread. Sleep (100 );
  88. }
  89. S = new string (baos. tobytearray ());}
  90. // Return results
  91. Return S;
  92. } Catch (exception e ){
  93. E. printstacktrace ();
  94. }
  95. Return NULL;
  96. }
  97. @ Override
  98. Protected void oncancelled (){
  99. Super. oncancelled ();
  100. }
  101. @ Override
  102. Protected void onpostexecute (string result ){
  103. // Return the HTML page content
  104. Message. settext (result );
  105. Pdialog. Dismiss ();
  106. }
  107. @ Override
  108. Protected void onpreexecute (){
  109. // Start the task. A dialog box is displayed here, which is simple.
  110. Message. settext (R. String. task_started );
  111. }
  112. @ Override
  113. Protected void onprogressupdate (integer... values ){
  114. // Update Progress
  115. System. Out. println ("" + values [0]);
  116. Message. settext ("" + values [0]);
  117. Pdialog. setprogress (Values [0]);
  118. }
  119. }
  120. }
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.