Android Asynctask Example Tutorial

author-image   By Sanjeev K. Saroj,   02 April, 2017 6K

This tutorial is about creating AsyncTask in android applications. In this article we will discuss about what is AsyncTask, how AsyncTask works in android application and develop an example application using AsyncTask that performs an abstract AsyncTask in background.

what is AsyncTask

AsyncTask is an abstract class provided by Android which enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around thread and Handler and does not constitute a generic threading framework. An AsyncTask name implies,executes a task asynchronously. The AsyncTask is a generic class that takes 3 types of arguments. - AsyncTask <Params, Progress, Result>

Params - the type that is passed into the execute() method.

Progress - the type that is used within the task to track progress.

Result - the type that is returned by doInBackground().

The type of the arguments passed when starting the task, the type of arguments returned to the caller when reporting progress, and the type of the result.

 Other Interesting Posts
CreateCustom Adpter in List view
Android Service Example
Broadcastreceiver Example Tutorial

Different AsyncTask Stages

AsyncTask will go through the following 4 stages:

onPreExecute():- It is invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface. This is also used to create dialog box and carry out initialization.

doInBackground(Params...):-The main purpose of AsyncTask is accomplished by this method. Any non-UI thread process is running in this method such as Rss Feed Reader,Image and video Uploading and Downloading. You cant handle your View in this method because this method is non-UI thread.

While any background process is running if you want to handle UI there are onProgressUpdate() method. After completion of process this method send result to OnPostExecute. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

onProgressUpdate(Progress...):- It is invoked on the UI thread after a call to publishProgress(). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

onPostExecute(Result):- It is invoked on the UI thread after the background computation finishes to process final data returned by doInBackgroundThe result of the background computation is passed to this step as a parameter.

AsyncTask LifeCycle

There is quite a misunderstanding about our AsyncTask. Developers might think that when the Activity that created the AsyncTask has been destroyed, the AsyncTask will be destroyed as well. This is not the case. The AsyncTask keeps on running, doing his doInBackground() method until it is done. Once this is done it will either go to the onCancelled(Result result) method if cancel(boolean) is invoked or the onPostExecute(Result result) method if the task has not been cancelled.

Suppose our AsyncTask was not cancelled before our Activity was destroyed. This could make our AsyncTask crash, because the view it wants to do something with, does not exist anymore. So we always have to make sure we cancel our task before our Activity is destroyed.

The cancel(boolean) method needs one parameter: a boolean called mayInterruptIfRunning. This should be true if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete. If there is a loop in our doInBackground() method, we might check the boolean isCancelled() to stop further execution. So we have to make sure the AsyncTask is always cancelled properly.

Android AsyncTask Example

Create an empty project in Android Studio. Create a class MyAsyncTask which extends AsyncTask , and override all methods. Following is the project structure.


Defining activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""

        android:text="Start AsyncTask"


This activity is basically to interact with user.In this activity we have given two url to call AsyncTask.

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends AppCompatActivity {

    Button btn_start;
    String  url = "";
    String  url1 = "";
    ImageView sourceImageView;

    protected void onCreate(Bundle savedInstanceState) {
        btn_start= (Button) findViewById(;

        sourceImageView= (ImageView) findViewById(;
        btn_start.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                 new MyAsyncTask().execute(url1);


    private class MyAsyncTask extends AsyncTask{
        ProgressDialog progressDialog;

        protected Bitmap doInBackground(String... strings) {

            String urldisplay = strings[0];
            Bitmap bitmap = null;
            try {
                InputStream in = new;
                bitmap = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());

            return bitmap;


        protected void onProgressUpdate(Integer... values) {

        protected void onPostExecute(Bitmap bitmap) {

            if(bitmap != null){

        protected void onPreExecute() {
            progressDialog =, "Downloading", "Downloading..Please Wait", true);



Defining AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""

    <uses-permission android:name="android.permission.INTERNET" />

        <activity android:name=".MainActivity">
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

NOTE:-Don't forgot to give INTERNET permission in android studio.

Following is the final screen.



I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Download source

If You Appreciate This, You Can Consider:

  • Like us at: Facebook or follow us at Twitter
  • Share this article on social media or with your teammates.
  • We are thankful for your never ending support.

About The Author


Android Developer at Tech Mahindra

Further Reading on Android

1 Create Custom Adapter In List View

2 Android Service Example

3 Android Broadcastreceiver Example Tutorial

4 Android Sqlite Database Example