Android AsyncTask asynchronous task, androidasynctask

Source: Internet
Author: User

Android AsyncTask asynchronous task, androidasynctask
In the previous article "using HttpClient for Get communication in Android Network Programming", we forced network operations directly in the UI thread. in actual application development, we could not do this, this may block the UI and affect the user experience. To avoid network operations in the UI thread, we can use AsyncTask to process network communication and UI updates asynchronously. Using AysncTask, you can easily start the background thread for network communication and then return the result to the UI thread.

AsyncTask is a lightweight asynchronous class provided by Android. It can inherit AsyncTask directly and implement asynchronous operations in the class, the interface is provided to feedback the degree of asynchronous execution (UI progress update can be implemented through the interface), and the execution result is finally fed back to the main UI thread.

AsyncTask is a helper class used to facilitate the compilation of background thread interaction with UI thread. Its internal implementation is a thread pool. Each background task is submitted to the thread pool for thread execution, then, the UI interface is updated by calling the corresponding callback method by passing messages to the UI thread. The AsyncTask class has three template parameters: Params (parameter type passed to the background task) and Progress (progress units, that is, the background program has executed a few percent) and Result (the type of the Result returned by the background execution ).

To use AsyncTask, you must at least rewrite the following two methods:
1. doInBackground (Params ...) The operations in the background can be put here. Note that you cannot directly operate the UI here. This method is executed in the background thread to complete the main work of the task, usually takes a long time. You can call publicProgress (Progress…) during execution ...) To update the task progress.
2. onPostExecute (Result) can be used in the Result processing UI obtained in doInBackground. This method is executed in the main thread, and the task execution result is returned as a parameter of this method.

When using the AsyncTask class, the following guidelines must be followed:
1. The Task instance must be created in the UI Thread;
2. The execute () method must be called in the UI Thread;
3. Do not manually call the onPreExecute (), onPostExecute (Result), doInBackground (Params...), onProgressUpdate (Progress...) methods;
4. The Task can only be executed once. Otherwise, exceptions may occur during multiple calls;

General steps for AsyncTask:
1. inherit the AsyncTask class and at least rewrite doInBackground (Params ...) And onPostExecute (Result) methods;
2. instantiate a subclass of AsyncTask;
3. Call the execute () method of the instance to start the task.

Entire Process:
The entire call process of AsyncTask starts from the execute () method (called in the main thread). Once the execute method is called in the main thread, the onPreExecute method is called, here, you can make some preparations, such as displaying a progress bar on the interface or instantiating some controls. you can also use the onProgressUpdate method to display updates to the progress bar to improve user experience. Finally, the onPostExecute method is used to process the UI operations in the results of doInBackground. The result of the doInBackground task is returned as a parameter of this method.

The following uses the aggregated data Air Quality City Air PM2.5 index data interface as an example to demonstrate the use of AsyncTask.

Instance: AsyncTaskDemo
Running effect:


Code List:
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: orientation = "vertical" tools: context = ". mainActivity "> <LinearLayout android: layout_width =" match_parent "android: layout_height =" wrap_content "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_weight = "3" android: inputType = "text"/> </LinearLayout> <Button android: id = "@ + id/query" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "query" android: textSize = "23sp"/> <TextView android: id = "@ + id/result" android: layout_width = "match_parent" android: 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 city = et_city.getText (). toString (); if (city. length () <1) {Toast. makeText (MainActivity. this, "enter the city name", Toast. LENGTH_LONG ). show (); return;} task = new QueryTask (MainActivity. this, TV _result); task.exe cute (city) ;}}) ;}@ Override public boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action 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/environment/air/pm "; private static final String JUHE_APPKEY = "Your applied APPKEY value"; p Ublic 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"); S Tring 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", city); for (int I = 0; I <paramList. size (); I ++) {NameValuePair nowPair = paramList. get (I); String value = nowPair. getVal Ue (); 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 


API knowledge point
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 having to manipulate threads 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) is invoked and doInBackground (Object []) has finished.

Void onCancelled ()
Applications shocould 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 be invoked from doInBackground (Params...) to publish updates on the UI thread while the background computation is still running.

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.