AsyncTask In Android Application

Hello Developers !!

Today we are going to understand the concept of AsynTask and Implement It. When we have  long lasting processing data at background and then update it on UI or main thread,then its a problematic situation. Then we have long lasting application blocking problems. To provide a good user experience all slow running operations in an Android application,we need to run process asynchronously. So,we need to use Handlers or AsyncTask.

At User Level, The user should get acknowledgment or Feedback about the background processing. So, we can show Progress Dialog View as a feedback message.

To Run Background Process and The Synchronization with main thread ,we require AsyncTask to be implemented. Tasks like fetching data and updating in the display adapters and so on or have login check process at background,Updating application data at background.

So ,Today we are going to implement AsyncTask.

  1. How to get to AsyncTask Class:
  2. Where to implement background process.
  3. How to show the Feedback View to application Users.
  4. How to step next after the long lasting process.

To use the AsyncTask class, Extend your class with:

AsyncTask<Parameter Datatype1,Progress Datatype2, Result Datatype3>

First parameter Datatype1: Parameters are passed when we start AsyncTask execution.

Second prarameter Datatype 2: progress value is passed to keep the user update with the running process.

Third parameter Datatype 3: Result is any data to send on the process completion.

AsyncTask Class provides mainly 4 methods:

  1. onPreExecute()
  2. doInBackground(String….)
  3. onProgressUpdate(String..)
  4. onPostExecute(String)

To start a AsyncTask at background ,we need to call by using execute() method.

 MyAsyncBackProcess backgndprocess=new MyAsyncBackProcess();

If You want to send parameter, you can send using

 backgndprocess.execute(new String[]{"loginname","password");

This execute() calls the doInBackground() method to start the process at background.

Then the onPreExecute() ,method is called. In this method we can initialize progress bar or initize the variables,DB object . Then background process starts. While background process is working on ..we can set message using logs or progress bar message if initialized on onProgressUpdate(). Once the background process is completed, onPostExecute() is called. On onPostExecute() we have options to whether intent to next activity on perform next action and send the process data. If we have initialized the progress bar,then we need to hide it because at this method the async thread is returned to main thread to show results.

onPreExecute() method:

protected void onPreExecute() {

doInBackground() method: This method is compulsory .

protected String doInBackground(String... params) {
    return null;

onProgressUpdate() method:

protected void onProgressUpdate(String... values) {

onPostExecute() method:

protected void onPostExecute(String s) {

Now let’s write a simple working of AsyncTask,

import android.content.Context;
import android.os.Bundle;
import android.os.AsyncTask;
import android.util.Log;

public class Login extends Activity {
    MyBackTask runner;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        runner = new MyBackTask();
    class MyBackTask extends AsyncTask<String,String,String> {
        String TAG = "asynctask_status";
        ProgressDialog progressDialog;
        Context context;
        int progress;
        @Override protected String doInBackground(String... params) {
            // Perform an operation on a background thread           
            Log.d(TAG, "MyAsyncTask@doInBackground from another thread");
                int i=0;
                    //Do operations here like connectivity check  
                    Log.d("pd status", "running" + i);
        }catch (InterruptedException ie){
            return null;
        @Override protected void onPostExecute(String s) {
            Log.d("pd status", "dismissed");

        @Override protected void onPreExecute() {
            progressDialog = new ProgressDialog(Login.this);
            Log.d("pd status", "created n displayed");

//        things to be done before execution of long running operations.example showing progress dialog

 @Override protected void onProgressUpdate(String... values) {
           Log.d("pd status", "in progress");
            //things to be done while execution of long running operation
            // eg. updating progress dialog            

Note : Don’t Forget the register Activtiy class in Manifest class.

Cancelling the task :

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of PostExecute(Object) will be invoked after doInBackground() returns. To ensure that a task is cancelled as  quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible(inside a loop for instance.)

3 thoughts on “AsyncTask In Android Application”

Leave a Reply

Your email address will not be published. Required fields are marked *