The usage of Asynctask _android

Source: Internet
Author: User
Tags http request

The principle of a single-threaded model must be followed when developing Android applications: Android UI operations are not thread-safe and must be performed in the UI thread. Always remember two rules in a single-threaded model:
1. Do not block UI threads
2. Ensure that the Android UI Toolkit is accessed only in the UI thread
When a program starts for the first time, Android also initiates a corresponding main thread (main thread), which is primarily responsible for handling UI-related events, such as user key events, user contact screen events, and screen drawing events, and distributing related events to the corresponding components for processing. So the main thread is often called the UI thread.
For example, from the Internet to obtain a Web page, in a TextView its source code display, this involves the network operation of the program is generally required to open a thread to complete the network access, but after the source of the page, is not directly in the network operation thread Call Textview.settext () . Because the main UI thread member cannot be accessed directly from other threads.

Android provides several ways to access UI threads in other threads.
Activity.runonuithread (Runnable) (Runnable)
View.postdelayed (Runnable, long)
These classes or methods also make your code very complex and difficult to understand. However, this can get worse when you need to implement some very complex operations and need to update the UI frequently.

To address this problem, Android 1.5 provides a tool class: Asynctask, which makes it easier to create long-running tasks that require interaction with the user interface. Asynctask is relatively lightweight, suitable for simple asynchronous processing, and does not require the help of threads and handler.
Asynctask is an abstract class. Asynctask defines three generic types 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 The results returned by the task, such as String.
The execution of Asynctask is divided into four steps, each of which corresponds to a callback method that should not be invoked by the application, and what the developer needs to do is implement these methods.
1) Sub-class of Asynctask
2 Implement the following one or several methods defined in Asynctask
OnPreExecute (), which is invoked by the UI thread before performing the actual background operation. You can do some preparation work in this method, such as displaying a progress bar on the interface.
Doinbackground (Params ...) is executed immediately after the OnPreExecute method is executed, which runs in a background thread. This will be the main responsibility for performing the time-consuming background computing work. You can call the Publishprogress method to update the real-time task progress. This method is an abstract method that must be implemented by subclasses.
Onprogressupdate (Progress ...), after the Publishprogress method is invoked, UI thread calls this method to show the progress of the task in the interface, for example, through a progress bar.
OnPostExecute (Result), after Doinbackground execution completes, the OnPostExecute method is invoked by the UI thread, and the results of the background calculation are passed to UI thread through this method.

For the correct use of the Asynctask class, here are a few guidelines to follow:
1 The instance of the task must be created in UI thread
2 The Execute method must be called in UI thread
3 Do not manually invoke OnPreExecute (), OnPostExecute (Result), Doinbackground (Params ...), Onprogressupdate (Progress ...) These several methods
4 The task can only be executed once, otherwise the exception will occur when multiple calls are made
The parameters of the Doinbackground method and the OnPostExecute must correspond, which are specified in the generic parameter list of the Asynctask declaration, the first is the parameter that is accepted by Doinbackground, and the second is the parameter that shows the progress. The third one returns and OnPostExecute incoming parameters for Doinbackground.

Get a Web page from the Internet and display its source code in a TextView

Copy Code code as follows:

Package test.list;
Import java.util.ArrayList;

Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpGet;
Import org.apache.http.impl.client.DefaultHttpClient;

Import Android.content.Context;
Import Android.content.DialogInterface;
Import Android.os.AsyncTask;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.TextView;

public class Networkactivity extends activity{
Private TextView message;
Private Button Open;
Private EditText URL;

public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (;
Message= (TextView) Findviewbyid (;
Url= (EditText) Findviewbyid (;
Open= (Button) Findviewbyid (;
Open.setonclicklistener (New View.onclicklistener () {
public void OnClick (View arg0) {
Connect ();


private void Connect () {
Pagetask task = new Pagetask (this);
Task.execute (Url.gettext (). toString ());

Class Pagetask extends Asynctask<string, Integer, string> {
Variable-length input parameters, corresponding to Asynctask.exucute ()
ProgressDialog Pdialog;
Public Pagetask {
Pdialog = new ProgressDialog (context, 0);
Pdialog.setbutton ("Cancel", new Dialoginterface.onclicklistener () {
public void OnClick (dialoginterface dialog, int i) {
Dialog.cancel ();
Pdialog.setoncancellistener (New Dialoginterface.oncancellistener () {
public void OnCancel (Dialoginterface dialog) {
Finish ();
Pdialog.setcancelable (TRUE);
Pdialog.setmax (100);
Pdialog.setprogressstyle (progressdialog.style_horizontal); ();

Protected string Doinbackground (String ... params) {


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 = (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);

Let thread hibernate 100ms
Thread.Sleep (100);
s = new String (Baos.tobytearray ()); }
return results
return s;
catch (Exception e) {
E.printstacktrace ();


return null;


protected void oncancelled () {
Super.oncancelled ();

protected void OnPostExecute (String result) {
Returns the contents of an HTML page
Message.settext (result);
Pdialog.dismiss ();

protected void OnPreExecute () {
Task start, you can display a dialog box here, simple to deal with
Message.settext (r.string.task_started);

protected void Onprogressupdate (Integer ... values) {
Update progress
System.out.println ("" "+values[0]);
Message.settext ("" "+values[0]);
Pdialog.setprogress (Values[0]);



Finally, it needs to be explained that Asynctask cannot completely replace threads, and that logic that is more complex in logic or needs to be executed repeatedly in the background may require a thread to implement.

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: 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.