Android AsyncTask Example

By | August 16, 2013
In this tutorial we will see how to use AsyncTask in your android application .

AsyncTask is an abstract class provided by android ,which helps in performing background operations and updating the results on the UI Thread.

Android AsyncTask Android AsyncTask doBackground Android AsyncTask  onPostUpdate UI


AsyncTask has 3 generic Types :

  1. Param : The parameter sent to the task upon execution
  2. Progress : The parameter sent during background computation to show progress unit
  3. Result : This Parameter presents result return by background computation

AsyncTask has 4 Steps :

  1. onPreExecute( ) : Invoke the UI Thread after the task is executed, This method is normally is used to setup the task .
  2. doInBackground(Param…) : Invoked on background thread immediately after the onPreExecute() finishes executing, This is generally used to perform background operation which takes long time.
  3. onProgressUpdate(Progress…) : Invoked on the UI thread after a call to publishProgress(Progress…) inside doInBackground() ,This method is generally used to show the progress of the task .
  4. onPostExecute(Result…) : Invoked on the UI thread after the background computation finishes. this method takes the parameter result which is returned by doInBackground() method .This method is generally the end of task , and where you can update the result

Using AsyncTask :

To Use AsyncTask , your class must subclass to it and must override at least one method doInBackground() and most often override one more method called onPostExecute to update the result, In this we will be focusing on using all the 4 methods of AsyncTask

Lets see an Example of AsyncTask

Project Detail

Project Name AsyncTaskDemo
Package com.pavan.asynctaskdemo
Minimum SDK API 8
Target SDK API 17
Theme Holo Light with Dark Action Bar

1. XML Layout

file :- activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="15dp" >

<EditText
android:id="@+id/et_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter The Text..." >

<requestFocus />
</EditText>

<Button
android:id="@+id/bt_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="Button" />

<ProgressBar
android:id="@+id/pb_id"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:visibility="invisible" />

<TextView
android:id="@+id/tv_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

2. Activiity

file:-MainActivity.java

package com.pavan.asynctaskdemo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {

EditText et;
TextView tv;
Button bt;
ProgressBar pb;

int progress_status;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();

bt.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

String Value = et.getText().toString();

new MyTask().execute(Value);

}
});

}

private void initializeViews() {

et = (EditText) findViewById(R.id.et_id);
bt = (Button) findViewById(R.id.bt_id);
tv = (TextView) findViewById(R.id.tv_id);
pb = (ProgressBar) findViewById(R.id.pb_id);
}

// creating asynctask
class MyTask extends AsyncTask <String, Integer, String>{

ProgressDialog pd;

@Override
protected void onPreExecute() {

super.onPreExecute();
progress_status = 0;
tv.setText("Loading...");

bt.setEnabled(false);
pb.setVisibility(View.VISIBLE);

}

@Override
protected String doInBackground(String... params) {

String result = params[0];

while (progress_status < 100) {

progress_status += 5;

publishProgress(progress_status);
SystemClock.sleep(200);

}

return result;
}

@Override
protected void onProgressUpdate(Integer... values) {

super.onProgressUpdate(values);

pb.setProgress(values[0]);
tv.setText("Loading " + values[0] + "%");

}

@Override
protected void onPostExecute(String result) {

super.onPostExecute(result);
et.setText("");
tv.setText(result);
pb.setVisibility(View.INVISIBLE);
bt.setEnabled(true);

}
}
}

  • Some question Pawan
    1>If a activity Close what will happen to Async Task?
    2>While Async Task can we Resume and Pause the Activity ?
    3>What is different between Handler thread and Async Task?

  • Good one

  • thanks for this mate, im not good with android that much so this will help