Android assyncTask example

AsyncTask is a class provided by android which gives the ability to perform heavy tasks in the background and keep the UI thread light. With the help of assyncTask you can keep the UI thread of your application responsive always.

The basic methods used in assync task are
  1. doInBackground – This method will execute the task which should be done in background and notify UI thread regarding task completion by using return statement
  2. onPreExecute – ┬áThis method will process the task which should be done before background task starts.
  3. onPostExecute – This method will execute after the completion of doInBackground. In this method you can perform UI operations
  4. onProgressUpdate – This method can receive the progress updates from the doInBackground method.

Code: AssyncTask example

private class MyAssyncTask extends AsyncTask<String, Void, Void> {

@Override
protected void onPreExecute() {

// here you can do required operations before starting background task
// usually this method is used to set values to variables used in background taks

}

@Override
protected Void doInBackground(String... urls) {

// here you can use the code to execute background task
// UI cannot be referenced in this method

return null;
}

@Override
protected void onPostExecute() {

// After completing background task this method will get executed
// you can access UI here
}
}

Use the below code to start assync task

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

    new MyAssyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "argument to doInBackground");

} else {

 new MyAssyncTask().execute("argument to doInBackground");
}

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

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