单击取消按钮时无法取消fileDownloadTask

时间:2018-12-01 04:59:05

标签: android firebase android-studio

我正在使用进度对话框中的download()功能从firebase一张一张下载许多图像。为此,我进入了FileDownloadTask的列表。现在,我想通过单击取消按钮来取消剩余图像的下载,因为我已在OnClickListener中实现了代码中所示的方法,但是该方法无效,图像将继续下载。

List<FileDownloadTask> downloadTaskList = new ArrayList<>();
protected void download() throws IOException, JSONException {
        setDownloadProgressDialoag();
        imageList = image.getImages();
        File file = new File(context.getExternalFilesDir(null), "Images");
        if (!file.exists()) {
            file.mkdir();
        }
        for (Image image : imageList) {
            String url = image.getImageUrl();
            File imageFile = new File(file, i + "_" + image.getName() + ".jpg");
            if (!imageFile.exists()) {
                downloadRef = FirebaseStorage.getInstance().getReferenceFromUrl(url);
                    FileDownloadTask task = downloadRef.getFile(imageFile);
                    downloadTaskList.add(task);
                    task.addOnCompleteListener(new OnCompleteListener<FileDownloadTask.TaskSnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<FileDownloadTask.TaskSnapshot> task) {
                            downloadProgressDialoag.incrementProgressBy(1);
                            downloadTaskList.remove(task);
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {

                        }
                    });
                    i++;
                }
        }
}

ProgressDialog

private void setDownloadProgressDialoag() {
        downloadProgressDialoag = new ProgressDialog(context, R.style.PackLoaderDialog);
        downloadProgressDialoag.setTitle("Downloading Images...");
        downloadProgressDialoag.setMax(Image.noOfImage);
        downloadProgressDialoag.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        downloadProgressDialoag.setCancelable(false);
        downloadProgressDialoag.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                for(FileDownloadTask fileDownloadTask : downloadTaskList){
                    fileDownloadTask.cancel();
                }
            }
        });
        downloadProgressDialoag.show();
    }

我做错了什么?请帮助我。

0 个答案:

没有答案