Android Asynctask Asynchronous task

Source: Internet
Author: User

In the previous article, "Using HttpClient to get communication with Android network programming," We force the network operation directly on the UI thread, which cannot be done during the actual application development process because it is likely to block the UI and affect the user experience. To avoid network operations directly in the UI thread, we can use Asynctask to handle network traffic and UI updates asynchronously. With Aysnctask, it is easy to start a background thread for network communication, and then return the results to the UI thread.

Asynctask is a lightweight asynchronous class provided by Android that can inherit Asynctask directly, implement asynchronous operations in a class, and provide interface feedback about the current level of asynchronous execution (UI progress updates can be implemented through an interface), and finally feedback the execution results to the UI main thread.

Asynctask is intended to facilitate the writing of auxiliary classes for background threads interacting with the UI thread, and its internal implementation is a thread pool, where each background task is committed to threads in the thread pool, and then the corresponding callback method is invoked to implement updates to the UI interface by passing the message to the UI thread. The Asynctask class has three template parameters: Params (the type of parameter passed to the background task), Progress (the type of Progress unit (Progress units) in the background calculation execution, which is the percentage of the background program has been executed, and result ( The type of results returned by the background execution).

Use Asynctask to override the following two methods at a minimum:
1, Doinbackground (Params ...) background execution, more time-consuming operations can be placed here. Note that it is not possible to manipulate the UI directly. This method is performed on a background thread, and it usually takes a long time to complete the task's main work. You can call Publicprogress (Progress ...) during execution. To update the progress of the task.
2. OnPostExecute (Result) can use the results in the Doinbackground to manipulate the UI. This method is executed on the main thread, and the result of the task execution is returned as a parameter to this method.

Using the Asynctask class, here are a few guidelines to follow:
1. The instance of the task must be created in the UI thread;
2. The Execute () method must be called in the UI thread;
3, do not manually call 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;

Asynctask General steps to use:
1. Inherit the Asynctask class and rewrite at least doinbackground (Params ...) and OnPostExecute (Result) method;
2, instantiate the subclass of Asynctask;
3. Call the Execute () method of the instance to start the task.

The entire process:
The entire invocation of Asynctask is initiated from the Execute () method (called in the main thread), and once the Execute method is called in the main thread, the OnPreExecute method is called, where you can do some preparatory work, such as displaying a progress bar on the interface, Or the instantiation of some controls. The Onprogressupdate method can also be used to give the user a progress bar display update, to increase the user experience, and finally through the OnPostExecute method, the results obtained in Doinbackground to handle the operation UI. The result of the Doinbackground task execution is returned as a parameter to this method.

The following also illustrates the use of the asynctask using the data interface for the aggregated data air quality City Air PM2.5 index.

Example: Asynctaskdemo
Operating effect:


Code Listing:
Layout file: Activity_main.xml
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "Vertical" tools:context= ". Mainactivity "> <linearlayout android:layout_width=" match_parent "android:layout_height=" Wrap_cont            Ent "android:orientation=" horizontal "> <textview android:layout_width=" wrap_content "            android:layout_height= "Wrap_content" android:layout_weight= "1" android:gravity= "center"            android:text= "City:" android:textsize= "23sp"/> <edittext android:id= "@+id/city" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:layout_we        ight= "3" android:inputtype= "text"/> </LinearLayout> <button android:id= "@+id/query" AndroidOid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "Query" Android:text Size= "23sp"/> <textview android:id= "@+id/result" android:layout_width= "Match_parent" an droid:layout_height= "Match_parent"/></linearlayout>

Java source code file: Mainactivity.java
Package Com.rainsong.asynctaskdemo;import Android.os.bundle;import Android.app.activity;import android.view.Menu; Import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.textview;import Android.widget.toast;public class MainActivity    Extends Activity {EditText et_city;    Button Btn_query;    TextView Tv_result;    Querytask task;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Et_city = (EditText) Findviewbyid (r.id.city);        Tv_result = (TextView) Findviewbyid (R.id.result);        Btn_query = (Button) Findviewbyid (r.id.query); Btn_query.setonclicklistener (New Onclicklistener () {public void OnClick (view view) {String CIT                y = Et_city.gettext (). toString (); if (City.length () < 1) {Toast.maketext (mainactivity.This, "Please enter city name", Toast.length_long). Show ();                Return                } task = new Querytask (mainactivity.this, Tv_result);            Task.execute (city);    }        }); } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the Actio        n Bar if it is present.        Getmenuinflater (). Inflate (R.menu.main, menu);    return true; }}

Java source code file: Querytask.java
Package Com.rainsong.asynctaskdemo;import Java.io.ioexception;import Java.net.urlencoder;import Java.util.arraylist;import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.message.basicnamevaluepair;import Org.apache.http.util.entityutils;import Android.content.context;import Android.os.asynctask;import Android.widget.textview;import Android.widget.toast;public class Querytask extends Asynctask<string, Void, String    > {context context;    TextView Tv_result; private static final String juhe_url_environment_air_pm = "http://web.juhe.cn:8080/env    IRONMENT/AIR/PM ";    private static final String Juhe_appkey = "The APPKEY value you applied for";        Public Querytask (context context, TextView Tv_result) {//TODO auto-generated constructor stub super (); This.context = Context     This.tv_result = Tv_result;        } @Override protected String Doinbackground (String ... params) {string city = Params[0];        arraylist<namevaluepair> headerlist = new arraylist<namevaluepair> (); Headerlist.add (New Basicnamevaluepair ("Content-type", "text/html;        Charset=utf-8 "));        String targeturl = juhe_url_environment_air_pm;        arraylist<namevaluepair> paramlist = new arraylist<namevaluepair> ();        Paramlist.add (New Basicnamevaluepair ("key", Juhe_appkey));        Paramlist.add (New Basicnamevaluepair ("Dtype", "JSON"));        Paramlist.add (New Basicnamevaluepair ("City");            for (int i = 0; i < paramlist.size (); i++) {Namevaluepair Nowpair = Paramlist.get (i);            String value = Nowpair.getvalue ();            try {value = Urlencoder.encode (value, "UTF-8"); } catch (Exception e) {} if (i = = 0) {TargetUrl + = ("?" + NowPair.getname () + "=" + value);            } else {TargetUrl + = ("&" + nowpair.getname () + "=" + value);        }} httpget HttpRequest = new HttpGet (targeturl); try {for (int i = 0; i < headerlist.size (); i++) {Httprequest.addheader (Headerlist.get (i). g            Etname (), Headerlist.get (i). GetValue ());            } HttpClient HttpClient = new Defaulthttpclient ();            HttpResponse HttpResponse = Httpclient.execute (HttpRequest); if (Httpresponse.getstatusline (). Getstatuscode () = = () {String strresult = entityutils.tostring (httpresp                Onse.getentity ());            return strresult;            } else {return null;        }} catch (IOException e) {e.printstacktrace ();    } return null;          } @Override protected void OnPostExecute (String result) {if (result! = null) {  Tv_result.settext (result);            } else {Toast.maketext (context, "Query failed", Toast.length_long). Show ();        Tv_result.settext (""); }    }    }


API Knowledge Points
Public abstract class
Asynctask
Extends Object

Android.os.asynctask<params, Progress, result>

Class Overview
Asynctask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without have to manipulate threa DS and/or handlers.

Public constructors
Asynctask ()
Creates a new asynchronous task.

static void Execute(Runnable Runnable)
Convenience version of Execute (object) for use with a simple Runnable Object.

Abstract Result Doinbackground(Params ... params)
Override This method to perform a computation on a background thread.

void oncancelled (Result result)
Runs on the UI thread after cancel (Boolean) was invoked and Doinbackground (object[]) has finished.

void Oncancelled ()
Applications should preferably override Oncancelled (Object).

void OnPostExecute(Result result)
Runs on the UI thread after Doinbackground (Params ...).

void OnPreExecute ()
Runs on the UI thread before Doinbackground (Params ...).

void Onprogressupdate (Progress ... values)
Runs on the UI thread after publishprogress (Progress ...) is invoked.

Final void Publishprogress (Progress ... values)
This method can is invoked from Doinbackground (Params ...) to publish updates on the UI thread while the background Computa tion is still running.

Android Asynctask Asynchronous task

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.