How to cancel an executing AsyncTask in Android?

AndroidApps/ApplicationsMobile Development

Before getting into example, we should know what is AsyncTask in android. AsyncTask going to do operations/actions in background thread and update on mainthread. While doing background operations on background thread, user can cancel operations by using the following code -

AsynTaskExample mAsyncTask = new AsyncTaskExample();

This example demonstrate about how to cancel an executing AsyncTask in android.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = ""
   xmlns:tools = ""
   android:id = "@+id/rootview"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   android:orientation = "vertical"
   android:background = "#c1c1c1"
   android:gravity = "center_horizontal"
   tools:context = ".MainActivity">
      android:id = "@+id/asyncTask"
      android:text = "Download"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content" />
      android:id = "@+id/image"
      android:layout_width = "300dp"
      android:layout_height = "300dp" />

In the above code when you click on button it going to download image from internet source and append to imageview.

Step 3 − Add the following code to src/

package com.example.andy.myapplication;

import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
   URL ImageUrl = null;
   InputStream is = null;
   Bitmap bmImg = null;
   ImageView imageView = null;
   AsyncTaskExample asyncTask = null;
   ProgressDialog p;
   protected void onCreate(Bundle savedInstanceState) {
      Button button = findViewById(;
      imageView = findViewById(;
      button.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
            asyncTask = new AsyncTaskExample();
   private class AsyncTaskExample extends AsyncTask {
      protected void onPreExecute() {
         p = new ProgressDialog(MainActivity.this);
         p.setMessage("Please wait...It is downloading");
         p.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
               Toast.makeText(MainActivity.this,"AsyncTask is stopped",Toast.LENGTH_LONG).show();
      protected Bitmap doInBackground(String... strings) {
         try {
            try {
            } catch (InterruptedException e) {
            ImageUrl = new URL(strings[0]);
            HttpURLConnection conn = (HttpURLConnection) ImageUrl .openConnection();
            is = conn.getInputStream();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            bmImg = BitmapFactory.decodeStream(is, null, options);
         } catch (IOException e) {
         return bmImg;
      protected void onPostExecute(Bitmap bitmap) {
         if(imageView! = null) {
         } else {

Step 4− Add the following code to manifest.xml

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = ""
   package = "com.example.andy.myapplication">
   <uses-permission android:name = "android.permission.INTERNET"/>
      android:allowBackup = "true"
      android:icon = "@mipmap/ic_launcher"
      android:label = "@string/app_name"
      android:roundIcon = "@mipmap/ic_launcher_round"
      android:supportsRtl = "true"
      android:theme = "@style/AppTheme">
      <activity android:name = ".MainActivity">
            <action android:name = "android.intent.action.MAIN" />
            <category android:name = "android.intent.category.LAUNCHER" />

In the above code we have given internet permission to fetch an image from internet source.

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

When you click on the above button, it will start a progressbar, click on any place rather than progressbar it will show the following screen.

The above screen clearly shows the async task is stopped and image is now downloaded from internet source.

If you dont stop async task it will download an image as shown above

Click here to download the project code

Published on 31-Jan-2019 12:30:59