Introduction

This article explains the AsyncTask class in Android.
Asynctask
AsyncTask is a class used when a process takes time to complete. Suppose that when we want to load and transfer data to the web then we use the Asynctask class. The AsyncTask class provides some methods, such as doInBackGround(), onPreExecut(), onPostExecute() and onPorgressUpdate().
Step 1
Create a project like this:
"New" -> "Android Application Project" then enter the application name and click "Next".
async1
Click "Next".
async3
Click "Next".
async5
Step 2
Create an XML file with the following:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical"
  6. android:background="#123456">
  7. <Button
  8. android:id="@+id/button"
  9. android:layout_width="match_parent"
  10. android:layout_height="wrap_content"
  11. android:onClick="readWebpage"
  12. android:text="Load Webpage" >
  13. </Button>
  14. <TextView
  15. android:id="@+id/textView"
  16. android:layout_width="match_parent"
  17. android:layout_height="match_parent"
  18. android:text="Example Text" >
  19. </TextView>
  20. </LinearLayout>
Step 3
I wrote the code which takes time inside doInBackground(). In doInBackGround the first step is to create a default HttpClient HttpClient httpclient=new DefaultHttpClient(). After creating an Http Client we will instantiate a class to handle the post request and a URL as a parameter HttpGet httpget=new HttpGet(url). "url" is the URL that you want to invoke to send data. httppost.setEntitiy(new UrlEncodeFromEntity). The URL encoding is used to encode the parameter that you want to send. At last, we execute our request through the instance of the HttpClient and receive the response. HttpResponse httpResponse=httpclient.execute(httpget). For reading the response obtain an input stream and consume it reading data in this way:
  1. Input Stream inputstream=httpResponse.getEntity().getContent()
Create a Java class file with the following:
  1. package com.asyntask;
  2. import java.io.BufferedReader;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import org.apache.http.HttpResponse;
  6. import org.apache.http.client.methods.HttpGet;
  7. import org.apache.http.impl.client.DefaultHttpClient;
  8. import android.app.Activity;
  9. import android.os.AsyncTask;
  10. import android.os.Bundle;
  11. import android.view.View;
  12. import android.widget.TextView;
  13. public class MainActivity extends Activity
  14. {
  15. private TextView txtView;
  16. /** Called when the activity is first created. */
  17. @Override
  18. public void onCreate(Bundle savedInstanceState)
  19. {
  20. super.onCreate(savedInstanceState);
  21. setContentView(R.layout.activity_main);
  22. txtView = (TextView) findViewById(R.id.textView);
  23. }
  24. private class DownloadWebPageTask extends AsyncTask < String, Void, String >
  25. {
  26. @Override
  27. protected String doInBackground(String...url1)
  28. {
  29. String response = "";
  30. for (String url: url1)
  31. {
  32. DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
  33. HttpGet httpGet = new HttpGet(url);
  34. try
  35. {
  36. HttpResponse execute = defaultHttpClient.execute(httpGet);
  37. InputStream inputStream = execute.getEntity().getContent();
  38. BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));
  39. String st = "";
  40. while ((st = buffer.readLine()) != null)
  41. {
  42. response += st;
  43. }
  44. }
  45. catch (Exception e)
  46. {
  47. e.printStackTrace();
  48. }
  49. }
  50. return response;
  51. }
  52. @Override
  53. protected void onPostExecute(String res)
  54. {
  55. txtView.setText(res);
  56. }
  57. }
  58. public void readWebpage(View view)
  59. {
  60. DownloadWebPageTask task = new DownloadWebPageTask();
  61. task.execute(new String[]
  62. {
  63. "http://www.google.com"
  64. });
  65. }
  66. }
Step 4
Android Manifest.Xml file
In the Android Manifest.xml file you will provide the internet permission to connect to the internet as in the following:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.asyntask"
  4. android:versionCode="1"
  5. android:versionName="1.0" >
  6. <uses-permission android:name="android.permission.INTERNET"></uses-permission>
  7. <uses-sdk
  8. android:minSdkVersion="8"
  9. android:targetSdkVersion="18" />
  10. <application
  11. android:allowBackup="true"
  12. android:icon="@drawable/ic_launcher"
  13. android:label="@string/app_name"
  14. android:theme="@style/AppTheme" >
  15. <activity
  16. android:name="com.asyntask.MainActivity"
  17. android:label="@string/app_name" >
  18. <intent-filter>
  19. <action android:name="android.intent.action.MAIN" />
  20. <category android:name="android.intent.category.LAUNCHER" />
  21. </intent-filter>
  22. </activity>
  23. </application>
  24. </manifest>