Android

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();
 backgndprocess.execute();

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:

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

doInBackground() method: This method is compulsory .

@Override
protected String doInBackground(String... params) {
    return null;
}

onProgressUpdate() method:

@Override
protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
}

onPostExecute() method:

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
}

Now let’s write a simple working of AsyncTask,

package com.xxx.xxxx.xxx;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;

public class Login extends Activity {
    MyBackTask runner;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        runner = new MyBackTask();
        runner.execute();
    }
    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");
             try{
                int i=0;
                while(i<=100){
                progress=i;
                i++;
                    //Do operations here like connectivity check  
                Thread.sleep(200);
                    Log.d("pd status", "running" + i);
          }
        }catch (InterruptedException ie){
                 ie.printStackTrace();
              }
            return null;
   }
        @Override protected void onPostExecute(String s) {
            progressDialog.dismiss();
            Log.d("pd status", "dismissed");
                   }

        @Override protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(Login.this);
            progressDialog.setCancelable(true);
            progressDialog.setMessage("Loading...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setProgress(0);
            progressDialog.show();
            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) {
            progressDialog.setProgress(progress);
           Log.d("pd status", "in progress");
            //things to be done while execution of long running operation
            // eg. updating progress dialog            
           super.onProgressUpdate(values);
        }
   }
}

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 *