Android AsyncTask Example Tutorial

Published on August 3, 2022

Anupam Chugh

Android AsyncTask Example Tutorial

Today we will look into Android AsyncTask. We will develop an Android example application that performs an abstract AsyncTask in background.

Android AsyncTask

Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive. Android application runs on a single thread when launched. Due to this single thread model tasks that take longer time to fetch the response can make the application non-responsive. To avoid this we use android AsyncTask to perform the heavy tasks in background on a dedicated thread and passing the results back to the UI thread. Hence use of AsyncTask in android application keeps the UI thread responsive at all times. The basic methods used in an android AsyncTask class are defined below :

  • doInBackground() : This method contains the code which needs to be executed in background. In this method we can send results multiple times to the UI thread by publishProgress() method. To notify that the background processing has been completed we just need to use the return statements
  • onPreExecute() : This method contains the code which is executed before the background processing starts
  • onPostExecute() : This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method
  • onProgressUpdate() : This method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update the UI thread

The three generic types used in an android AsyncTask class are given below :

  • Params : The type of the parameters sent to the task upon execution
  • Progress : The type of the progress units published during the background computation
  • Result : The type of the result of the background computation

Android AsyncTask Example

To start an AsyncTask the following snippet must be present in the MainActivity class :

MyTask myTask = new MyTask();

In the above snippet we’ve used a sample classname that extends AsyncTask and execute method is used to start the background thread. Note:

  • The AsyncTask instance must be created and invoked in the UI thread.
  • The methods overridden in the AsyncTask class should never be called. They’re called automatically
  • AsyncTask can be called only once. Executing it again will throw an exception

In this tutorial we’ll implement an AsyncTask that makes a process to go to sleep for a given period of time as set by the user.

Android Async Task Project Structure

android asynctask, android asynctask example

Android AsyncTask Example Code

The xml layout is defined in the activity_main.xml and its given below: activity_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    tools:context=".MainActivity" >

        android:text="Sleep time in Seconds:"/>
        android:text="Run Async task"
        android:layout_marginTop="64dp" />
        android:layout_centerHorizontal="true" />

In the above layout we’ve used a predefined drawable as the border of the EditText. The MainActivity.java is defined below:

package com.journaldev.asynctask;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private Button button;
    private EditText time;
    private TextView finalResult;

    protected void onCreate(Bundle savedInstanceState) {
        time = (EditText) findViewById(R.id.in_time);
        button = (Button) findViewById(R.id.btn_run);
        finalResult = (TextView) findViewById(R.id.tv_result);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                AsyncTaskRunner runner = new AsyncTaskRunner();
                String sleepTime = time.getText().toString();

    private class AsyncTaskRunner extends AsyncTask<String, String, String> {

        private String resp;
        ProgressDialog progressDialog;

        protected String doInBackground(String... params) {
            publishProgress("Sleeping..."); // Calls onProgressUpdate()
            try {
                int time = Integer.parseInt(params[0])*1000;

                resp = "Slept for " + params[0] + " seconds";
            } catch (InterruptedException e) {
                resp = e.getMessage();
            } catch (Exception e) {
                resp = e.getMessage();
            return resp;

        protected void onPostExecute(String result) {
            // execution of result of Long time consuming operation

        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(MainActivity.this,
                    "Wait for "+time.getText().toString()+ " seconds");

        protected void onProgressUpdate(String... text) {

In the above code we’ve used AsyncTaskRunner class to perform the AsyncTask operations. The time in seconds is passed as a parameter to the class and a ProgressDialog is displayed for the given amount of time. The images given below are the outputs produced by the project where the time set by the user is 5 seconds. android asynctask example, AsyncTask This brings an end to the tutorial. You can download the final Android AsyncTask Project from the below link.

Download Android AsyncTask Example Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Anupam Chugh


While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
DigitalOcean Employee
DigitalOcean Employee badge
October 3, 2021

Please sir how can I use Async Task to display an image or a progress bar while another activity loads?

- Chibuzor Olumor

    DigitalOcean Employee
    DigitalOcean Employee badge
    September 1, 2020

    i have problem : i have a class MainActivity and i create an other class (public class MySql extends AsyncTask) i have return boolean value and now i want get this value , so how ???

    - sirine

      DigitalOcean Employee
      DigitalOcean Employee badge
      January 13, 2020

      Very helpful to understand and implement AsyncTask abstract class as a Helper class.

      - Umair

        DigitalOcean Employee
        DigitalOcean Employee badge
        August 9, 2019

        java.io.IOException: Cannot run program “su”: error=13, Permission denied I got this error when I used your code for updating an android app from website stored apk.

        - jaypal

          DigitalOcean Employee
          DigitalOcean Employee badge
          June 16, 2019

          Hi. Is there any possibility of returning an object from Async Task and using the attributes of that object in my main activity? Eg: I have an Async Task with parameters(void,void,Uaclient) { … protected Uaclient doInBackground(){…return client} protected onPostExecute(Uaclient client){} } how to access this client in Mainactivity? I get a NullPointer error

          - Rakshan Premsagar Kapikad

            DigitalOcean Employee
            DigitalOcean Employee badge
            March 17, 2019

            Your stuffs are great.God bless u

            - SAJAN.V

              DigitalOcean Employee
              DigitalOcean Employee badge
              January 12, 2019

              Hello ,Goodevening Your stuff is best it helps me a lot but i just have one doubt plz give me a solution for it i have done image slider exmaple using viewflipper the image slides properly but when i touch it it does not stops it stilss keep on sliding what should i implement so that whenever i long press the image should stop sliding n when i lift my finger it gets started again please help me though this please thankyou

              - Faizan

                DigitalOcean Employee
                DigitalOcean Employee badge
                October 24, 2018

                By using Asynctask connect from one activity into another activity(intent) example in android…

                - Raja

                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 3, 2018

                  I have a question. I have created a project. I must that two asyntask methods need work at same time on the project. But I can not do with asyntask. What can you advise me? Thanks for the answer.

                  - Abbos

                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    July 31, 2018

                    Superb article… I was on my final year mini project, I was stuck when NetworkonMainThread Exception came. I searched google docs asynctask but it makes me more confused. But you did really great. For beginners like me, these type of blog posts is needed.

                    - athira

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Featured on Community

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more
                      DigitalOcean Cloud Control Panel