Cannot cancel fileDownloadTask on cancel Button click

只愿长相守 提交于 2020-01-06 07:19:08

问题


I am downloading many images from firebase one by one by download() function with the progress dialog. For that, I made on the list of FileDownloadTask. Now I want to cancel the download for remaining images on cancel button click for that I implemented the method in OnClickListener as shown in the code but It won't work and images are going to continue downloading.

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();
    }

What thing I am doing wrong? Please help me.

来源:https://stackoverflow.com/questions/53567892/cannot-cancel-filedownloadtask-on-cancel-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!