AsyncTask Class in Android

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().
  • doInBackGround(): This method is the one that takes time to complete. So when you perform a click operation of a button it calls execute() and then the doInBackGround() method will be called.
  • onPreExecute(): This method is called before the doInBackGround() method is to run on the UI thread.
  • onPostExecute(): This method is called after the doInBackGround() method runs on the UI thread. The result from the doInBackGround() method is ed to this method.
  • onProgressUpdate(): This method is called by the doInBackGround() method to publish progress to the UI thread.
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.    
  8.         <Button  
  9.             android:id="@+id/button"  
  10.             android:layout_width="match_parent"  
  11.             android:layout_height="wrap_content"  
  12.             android:onClick="readWebpage"  
  13.             android:text="Load Webpage" >  
  14.         </Button>  
  15.    
  16.         <TextView  
  17.             android:id="@+id/textView"  
  18.             android:layout_width="match_parent"  
  19.             android:layout_height="match_parent"  
  20.             android:text="Example Text" >  
  21.         </TextView>  
  22.    
  23.     </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.   
  6. import org.apache.http.HttpResponse;  
  7. import org.apache.http.client.methods.HttpGet;  
  8. import org.apache.http.impl.client.DefaultHttpClient;  
  9.   
  10. import android.app.Activity;  
  11. import android.os.AsyncTask;  
  12. import android.os.Bundle;  
  13. import android.view.View;  
  14. import android.widget.TextView;  
  15.   
  16. public class MainActivity extends Activity   
  17. {  
  18.  private TextView txtView;  
  19.   
  20.  /** Called when the activity is first created. */  
  21.   
  22.  @Override  
  23.  public void onCreate(Bundle savedInstanceState)   
  24.  {  
  25.   super.onCreate(savedInstanceState);  
  26.   setContentView(R.layout.activity_main);  
  27.   txtView = (TextView) findViewById(R.id.textView);  
  28.  }  
  29.   
  30.  private class DownloadWebPageTask extends AsyncTask < String, Void, String >   
  31.  {  
  32.   @Override  
  33.   protected String doInBackground(String...url1)   
  34.   {  
  35.    String response = "";  
  36.    for (String url: url1)   
  37.    {  
  38.     DefaultHttpClient defaultHttpClient = new DefaultHttpClient();  
  39.     HttpGet httpGet = new HttpGet(url);  
  40.     try   
  41.     {  
  42.      HttpResponse execute = defaultHttpClient.execute(httpGet);  
  43.      InputStream inputStream = execute.getEntity().getContent();  
  44.   
  45.      BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));  
  46.      String st = "";  
  47.      while ((st = buffer.readLine()) != null)   
  48.      {  
  49.       response += st;  
  50.      }  
  51.   
  52.     }   
  53.     catch (Exception e)   
  54.     {  
  55.      e.printStackTrace();  
  56.     }  
  57.    }  
  58.    return response;  
  59.   }  
  60.   
  61.   @Override  
  62.   protected void onPostExecute(String res)   
  63.   {  
  64.    txtView.setText(res);  
  65.   }  
  66.  }  
  67.   
  68.  public void readWebpage(View view)   
  69.  {  
  70.   DownloadWebPageTask task = new DownloadWebPageTask();  
  71.   task.execute(new String[]   
  72.   {  
  73.    "http://www.google.com"  
  74.   });  
  75.   
  76.  }  
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.    
  7.     <uses-permission android:name="android.permission.INTERNET"></uses-permission>  
  8.      
  9.     <uses-sdk  
  10.         android:minSdkVersion="8"  
  11.         android:targetSdkVersion="18" />  
  12.    
  13.     <application  
  14.         android:allowBackup="true"  
  15.         android:icon="@drawable/ic_launcher"  
  16.         android:label="@string/app_name"  
  17.         android:theme="@style/AppTheme" >  
  18.         <activity  
  19.             android:name="com.asyntask.MainActivity"  
  20.             android:label="@string/app_name" >  
  21.             <intent-filter>  
  22.                 <action android:name="android.intent.action.MAIN" />  
  23.    
  24.                 <category android:name="android.intent.category.LAUNCHER" />  
  25.             </intent-filter>  
  26.         </activity>  
  27.     </application>  
  28. </manifest> 


Similar Articles