如何在android中停止(杀死)AsyncTask

Utt*_*dam 4 android gridview asynchronous

嗨我是android的新手:

我在GridView中显示图像拇指.为了获得更好的性能,我将异步加载它.

我的AsyncTask如下:

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

和电话表格:

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;
    }
Run Code Online (Sandbox Code Playgroud)

这里的问题是即使我点击后退按钮,任务也在后台运行.

Veg*_*ger 15

使用cancel()停止AsyncTask:

task.cancel(true);
Run Code Online (Sandbox Code Playgroud)

AsyncTask文档在"取消任务"部分中提供了一些其他详细信息:

可以通过调用cancel(boolean)随时取消任务.调用此方法将导致后续调用isCancelled()返回true.调用此方法后,onCancelled(对象),而不是 onPostExecute(对象)将后调用doInBackground(对象[])的回报.为确保尽快取消任务,应始终定期从doInBackground(Object [])检查isCancelled()的返回值,如果可能的话(例如在循环内).


Sam*_*uel 5

首先,您需要保持对每个执行的asynctask的引用.当活动暂停时,您应该遍历对asynctask的引用并使用cancel()取消它们.你还应该在每个asynctasks上调用get().这将确保UI线程在更改活动之前等待asynctask完成.

如果你想让asynctask的线程被中断,或者使用cancel(false),请使用cancel(true),并且在doInBackground()方法中的点处,你应该检查isCancelled()并返回.

为了安全起见,你必须非常小心asynctasks.查看这篇关于安全处理它们的文章.