Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop ( kill ) AsyncTask in android

Hi I am new to android:

I am displaying image thumbs in GridView. For better performance I am loading it asynchronously.

My AsyncTask is as:

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
        private final WeakReference<ImageView> imageViewReference;
        private int data = 0;
        private String image_path;

        public BitmapWorkerTask(ImageView imageView) {
            imageViewReference = new WeakReference<ImageView>(imageView);
        }

        @Override
        protected Bitmap doInBackground(Integer... params) {
            data = params[0];
            Bitmap picture = BitmapFactory.decodeFile(image_path);
            int width = picture.getWidth();
            int height = picture.getHeight();
            float aspectRatio = (float) width / (float) height;
            int newWidth = 98;
            int newHeight = (int) (98 / aspectRatio);
            return picture = Bitmap.createScaledBitmap(picture, newWidth,
                    newHeight, true);

        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (imageViewReference != null && bitmap != null) {
                final ImageView imageView = imageViewReference.get();
                if (imageView != null) {
                    imageView.setImageBitmap(bitmap);
                }

            }
        }

        public void onDismiss(DialogInterface dialog) {
            this.cancel(true);
        }
    }

and Calling form:

public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater layoutInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ListRowHolder listRowHolder;
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.ll_sponsor_list_item,
                    parent, false);
            listRowHolder = new ListRowHolder();
            listRowHolder.imgSponsor = (ImageView) convertView
                    .findViewById(R.id.imggrid_item_image);
            convertView.setTag(listRowHolder);

        } else {
            listRowHolder = (ListRowHolder) convertView.getTag();
        }
        try {
            BitmapWorkerTask task = new BitmapWorkerTask(
                    listRowHolder.imgSponsor);
            task.image_path = ImageName.get(position);
            task.execute(1);

        } catch (Exception e) {
            Toast.makeText(ctx, e + "", Toast.LENGTH_SHORT).show();
        }

        return convertView;
    }

The problem here is the tasks are running in background even I clicked on back button.

like image 834
Uttam Kadam Avatar asked Nov 30 '22 04:11

Uttam Kadam


2 Answers

Use cancel() to stop a AsyncTask:

task.cancel(true);

The documentation of AsyncTask provides some additional details in the 'Cancelling a task' section:

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

like image 59
Veger Avatar answered Dec 04 '22 00:12

Veger


First, you need to keep references to every asynctask you execute. When the activity pauses, you should iterate through the references to the asynctask and cancel them with cancel(). You should also call get() on each of the asynctasks. This will make sure that the UI thread waits until the asynctask is finished before changing activities.

Use cancel(true) if you want the asynctask's thread to be interrupted, or use cancel(false), and at points in your doInBackground() method you should check isCancelled() and return.

For safety you must be very careful with asynctasks. Check out this article on safely handling them.

like image 40
Samuel Avatar answered Dec 04 '22 01:12

Samuel