Asynctask usage examples sharing _android in Android

Source: Internet
Author: User

* Asynctask

It appears that the modified connect () method is available, but the way of this anonymous thread is flawed: first, the thread is expensive, and if each task is to create a thread, then the application is much less efficient; second, the thread is not manageable, When an anonymous thread is created and started, it is not controlled by the program, and if there are many requests sent, a very large number of threads will be started and the system will be overwhelmed. Also, as you've seen earlier, updating the UI in a new thread must also introduce handler, which makes the code look bloated.

To address this problem, OPhone introduced Asynctask in version 1.5. The Asynctask feature is that the task runs outside the main thread, and the callback method is executed in the main thread, which effectively avoids the hassle of using the handler. Read the source of Asynctask, Asynctask is using the Java.util.concurrent framework to manage the thread and the execution of the task, concurrent framework is a very mature, efficient framework, after rigorous testing. This shows that the Asynctask design solves the problem of the anonymous thread very well.

Asynctask is an abstract class, and subclasses must implement abstract methods Doinbackground (Params ... p) to implement tasks in this method, such as connecting network access data. It is also common to implement the OnPostExecute (Result R) method because the results of the application's concerns are returned in this method. It is important to note that Asynctask must create an instance in the main thread. Asynctask defines three generic types of params,progress and result.

* Params The input parameters that start the task execution, such as the URL of the HTTP request.
* Progress The percentage of background task execution.
* Result background to perform the final return of the task, such as String.

The execution of Asynctask is divided into four steps, similar to the Tasklistener defined earlier. Each step corresponds to a callback method, it should be noted that these methods should not be called by the application, developers need to do is to implement these methods. These methods are invoked automatically during the execution of a task.

* OnPreExecute () to call this method before the task executes, you can display the progress dialog box here.
* Doinbackground (Params ...) This method is performed in a background thread, and it usually takes a long time to complete the task's main work. Publicprogress can be invoked during execution (Progress ...) To update the progress of the task.
* Onprogressupdate (Progress ...) This method executes on the main thread to show the progress of the task execution.
* OnPostExecute (Result) This method executes in the main thread, and the results of the task execution are returned as parameters of this method.

Pagetask expands the Asynctask and reads the contents of the Web page in the Doinbackground () method. Pagetask's source code looks like this:

Copy Code code as follows:

Set three types of parameters, respectively, string,integer,string
Class Pagetask extends Asynctask<string, Integer, string> {

Variable-length input parameters, corresponding to Asynctask.exucute ()
@Override
Protected string Doinbackground (String ... params) {
try {
HttpClient client = new Defaulthttpclient ();
Params[0] represents the URL of a connection
HttpGet get = new HttpGet (params[0]);
HttpResponse response = Client.execute (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[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 length of the response, call publishprogress () Update progress
Publishprogress ((int) ((Count/(float) length) * 100);
}
In order to see progress clearly in the simulator, let the thread hibernate 100ms
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) {
Returns the contents of an HTML page
Message.settext (result);
}
@Override
protected void OnPreExecute () {
Task start, you can display a dialog box here, simple to deal with
Message.settext (r.string.task_started);
}
@Override
protected void Onprogressupdate (Integer ... values) {
Update progress
Message.settext (Values[0]);
}
}

Executing pagetask is very simple and requires only the following code to be invoked. Rerun Networkactivity, not only can crawl the content of the Web page, also can update the progress of reading in real time. The reader tries to read a larger page to see the percentage update.

Copy Code code as follows:

Pagetask task = new Pagetask ();
Task.execute (Url.gettext (). toString ());

Download instance: Testasync (jb51.net). rar

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.