How to cancel an executing AsyncTask in Android?


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();
mAsyncTask.cancel(true);

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 = "http://schemas.android.com/apk/res/android"
   xmlns:tools = "http://schemas.android.com/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">
   <Button
      android:id = "@+id/asyncTask"
      android:text = "Download"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content" />
   <ImageView
      android:id = "@+id/image"
      android:layout_width = "300dp"
      android:layout_height = "300dp" />
</LinearLayout>

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/MainActivity.java

package com.example.andy.myapplication;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
   URL ImageUrl = null;
   InputStream is = null;
   Bitmap bmImg = null;
   ImageView imageView = null;
   AsyncTaskExample asyncTask = null;
   ProgressDialog p;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Button button = findViewById(R.id.asyncTask);
      imageView = findViewById(R.id.image);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            asyncTask = new AsyncTaskExample();
            asyncTask.execute("https://www.tutorialspoint.com/images/tp-logo-diamond.png");
         }
      });
   }
   private class AsyncTaskExample extends AsyncTask {
      @Override
      protected void onPreExecute() {
         super.onPreExecute();
         p = new ProgressDialog(MainActivity.this);
         p.setMessage("Please wait...It is downloading");
         p.setIndeterminate(true);
         p.setCancelable(true);
         p.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
               asyncTask.cancel(true);
               Toast.makeText(MainActivity.this,"AsyncTask is stopped",Toast.LENGTH_LONG).show();
            }
         });
         p.show();
      }
      @Override
      protected Bitmap doInBackground(String... strings) {
         try {
            try {
               Thread.sleep(10000);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
            ImageUrl = new URL(strings[0]);
            HttpURLConnection conn = (HttpURLConnection) ImageUrl .openConnection();
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            bmImg = BitmapFactory.decodeStream(is, null, options);
         } catch (IOException e) {
            e.printStackTrace();
         }
         return bmImg;
      }
      @Override
      protected void onPostExecute(Bitmap bitmap) {
         super.onPostExecute(bitmap);
         if(imageView! = null) {
            p.hide();
            imageView.setImageBitmap(bitmap);
         } else {
            p.show();
         }
      }
   }
}

Step 4− Add the following code to manifest.xml

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
   package = "com.example.andy.myapplication">
   <uses-permission android:name = "android.permission.INTERNET"/>
   <application
      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">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />
            <category android:name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

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

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements