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:
-
- // Set three types of parameters: String, integer, and string.
-
- Class pagetask extends asynctask <string, integer, string> {
-
-
-
- // Variable length input parameter, which corresponds to asynctask. exucute ()
-
- @ Override
-
- Protected string doinbackground (string... Params ){
-
- Try {
-
- Httpclient client = new defaulthttpclient ();
-
- // Params [0] indicates the URL of the connection.
- Httpget = new httpget (Params [0]);
-
- Httpresponse response = client.exe cute (get );
-
- Httpentity entity = response. getentity ();
-
- Long length = entity. getcontentlength ();
-
- Inputstream is = entity. getcontent ();
-
- String S = NULL;
-
- If (is! = NULL ){
-
- Bytearrayoutputstream baos = new bytearrayoutputstream ();
- Byte [] Buf = new byte [1, 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 progress.
-
- 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 results
-
- Return S;
-
- } Catch (exception e ){
-
- E. printstacktrace ();
-
- }
-
- Return NULL;
-
- }
-
- @ Override
-
- Protected void oncancelled (){
- Super. oncancelled ();
-
- }
-
- @ Override
-
- Protected void onpostexecute (string result ){
-
- // Return the HTML page content
-
- Message. settext (result );
-
- }
-
- @ Override
-
- Protected void onpreexecute (){
-
- // Start the task. A dialog box is displayed here, which is simple.
-
- Message. settext (R. String. task_started );
-
- }
- @ Override
-
- Protected void onprogressupdate (integer... values ){
-
- // Update Progress
-
- Message. settext (Values [0]);
-
- }
-
- }
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.
- Pagetask task = new pagetask ();
- Task.exe cute (URL. gettext (). tostring ());
Copy code