Asynctask
It seems that the modified connect () method is available, but this anonymous thread method has a defect: first, the thread overhead is large. If each task needs to create a thread, then the application
The program efficiency is much lower. Second, the thread 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 have seen that handler must be introduced to update the UI in the new thread, which makes the Code look 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. the concurrent framework is used to manage threads and task execution. The concurrent framework is a very mature and efficient framework that has been rigorously tested. This shows that the design of asynctask is a good solution.
Problems with 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. The source code of pagetask is as follows:
// Set three types of parameters: String, integer, string class pagetask extends asynctask <string, integer, string> {// variable length input parameters, and asynctask. exucute () corresponds to @ override protected string doinbackground (string... params) {try {httpclient client = new defaulthttpclient (); // Params [0] indicates the URL of the connection httpget get = new httpget (Params [0]); httpresponse response = client.exe cute (get); httpentity entity = response. getentity (); long lengt H = entity. getcontentlength (); inputstream is = entity. getcontent (); string S = NULL; If (is! = NULL) {bytearrayoutputstream baos = new bytearrayoutputstream (); byte [] Buf = new byte [128]; int CH =-1; int COUNT = 0; while (CH = is. read (BUF ))! =-1) {baos. write (BUF, 0, CH); count + = CH; If (length> 0) {// if you know the response length, call publishprogress () to update the publishprogress (INT) (count/(float) length) * 100);} // to clearly view the progress in the simulator, sleep the thread for 100 ms thread. sleep (100);} s = new string (baos. tobytearray ();} // return s;} catch (exception e) {e. printstacktrace ();} return NULL;} @ override protected void oncancelled () {super. oncancelled () ;}@ override protected void onpostexecute (string result) {// return the message of the HTML page. settext (result) ;}@ override protected void onpreexecute () {// start the task. A dialog box is displayed here, where message is simply processed. settext (R. string. task_started) ;}@ override protected void onprogressupdate (integer... values) {// update progress message. settext (Values [0]) ;}}
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.
PageTask task = new PageTask(); task.execute(url.getText().toString());
Source code download