Android : 从 Firebase 存储下载文件列表

Android : download files list from Firebase storage

我向 Firebase 上传了一个文件列表,我想使用我的应用下载它。

List<String> childsRef = new ArrayList<>();
childsRef.add("xxxx/img1");    
childsRef.add("xxxx/img2");
... etc

然后,通过这个列表,我尝试使用我的 Firebase storageReference 下载文件:

for (String child : childsRef) {
    islandRef = storageRef.child(child);
    File localFile = File.createTempFile("images", "jpg");
    islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
       @Override
       public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
       // Local temp file has been created
       }
    }).addOnFailureListener(new OnFailureListener() {
       @Override
       public void onFailure(@NonNull Exception exception) {
       // Handle any errors
       }
 });
}

下载过程是异步的,所以我无法显示弹出窗口来可视化下载进度...我想导航到下一个 Activity 只有当所有待处理的下载都完成时..

你有ideas/help吗?

--编辑 解决方案:

FirebaseStorage instance = FirebaseStorage.getInstance();
StorageReference referenceFromUrl = instance.getReferenceFromUrl("gs://xxxxxxx.appspot.com/");

for (final String aur : aurl) {
    final File localFile = new File(PATH + aur.substring(aur.lastIndexOf("/") + 1, aur.lastIndexOf(".")) + ".dat");

    StorageReference f = referenceFromUrl.child(aur);

    FileDownloadTask task = f.getFile(localFile);

    task.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
            size += localFile.length();
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            Log.e("firebase ", ";local tem file not created  created " + exception.toString());
        }
    });

    while (!task.isComplete()) {
    }

    publishProgress("" + (int) ((float) i++ * 100 / aurl.length));

}

制作 childsRef hashmap 并添加一个布尔值以查看下载是否完成。 onSuccess 时设置值为 true 并使处理程序在下载完成时发送消息以检查所有布尔值是否为 true。比从处理程序开始你的 activity。

getFile returns a FileDownloadTask object, which is a subclass of Task. As you probably know, this Task tracks the progress of the download. You have the option of kicking off all the downloads at once, collecting all the Tasks in a list, then using Tasks.whenAll() 获取一个新任务,该任务在所有下载完成后完成。

four part blog series 关于使用 Tasks 可能会帮助您更好地理解它们的工作原理。