Android DownloadManager remove() - 如何确定 remove() 操作何时完成?

标签 android android-download-manager download-manager

是否有一种简单的机制来确定 DownloadManager remove() 何时完成,因为它看起来是部分异步的。该函数几乎立即返回下载表中已删除的条目计数,但实际的文件系统管理似乎被插入了某个后台线程。

问题是我写了一些代码,在提取新副本之前查找并删除文件 X(希望是文件系统对象)的任何现有 DownloadManager 条目。不幸的是,对于前一个版本,新副本在文件系统管理开始之前就进入了目录。所以管家实际上最终会在某个时候删除新版本并在 DownloadManager 表中留下一个孤立的条目。

可以用某种方法来阻止,直到文件系统删除操作完成。

调试代码:

    DownloadManager.Query query = new DownloadManager.Query().setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
    downloads = getAllDownloadIds(manager.query(query));

    path = activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);

    //If a file name was passed remove any existing entry / version of the file
    if ( fileName != null && ! fileName.isEmpty() ){
        if ( downloads.containsKey(fileName)){
            ids = downloads.get(fileName);
            for (Long id : ids) {
                Uri path = manager.getUriForDownloadedFile(id);
                File checkFile = new File(path.toString());
                Log.e(TAG, "Removing existing file: " + path.toString() + ":" + id);
                int entriesRemoved = manager.remove(id);
                Log.e(TAG, "Existing files removed: " + entriesRemoved);                  
            }
        }
    }


...
Log.v(TAG, "Attempting to create a file in the 'Download' directory on the external storage::" + path.toString() +"/"+ fileName);
file = new File(path, fileName);
Log.v(TAG, "Does the file already exist::" + file.exists());

示例输出:

… V/Export﹕ Removing existing file: file:///storage/sdcard/Download/appData.csv:101
… V/Export﹕ Existing files removed: 1
… V/Export﹕ Attempting to create a file in the 'Download' directory on the external storage::/storage/sdcard/Download/appData.csv
… V/Export﹕ Does the file already exist::true

最佳答案

我遇到了同样的问题 - 在快速网络中替换小文件时,替换文件有时会在调用 DownloadManager.remove(...) 后几分之一秒内到达。在这种情况下, 新到达的文件将被删除。

我使用的解决方案是,在调用 DownloadManager.remove(...) 之前,我设置了一个 FileObserver监视文件。然后我调用 remove(...),然后等待 DELETE 事件触发,然后再启动替换下载。

这最终导致大量代码分布在多个类中。还有其他复杂因素——例如,我设置了一个超时机制,以防下载管理器永远不会删除文件。 (我无法想象为什么它不会,但它不是我的组件)。

所以在回答“是否有一种简单的机制......”这个问题时:有一些机制可供你使用,但不幸的是不是特别简单的机制。

关于Android DownloadManager remove() - 如何确定 remove() 操作何时完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26269217/

相关文章:

Android更新应用跨应用重启使用DownloadManager(避免多次下载)

android - 在 Android 中使用 DownloadManager 从标题中获取文件名

安卓 : How to pause and resume using DownloadManager?

iphone - iOS应用程序后台下载

android - 如何通过代码打开手机图库

android - 调用 AAssetManager_fromJava 时崩溃 : "JNI WARNING: instance fieldID 0x571819bc not valid"

android - 将 Mupdf 库用于 pdfrenderer 不起作用

java - Gson在JAVA Android中将 boolean 值从1反序列化为false

android - 在不使用 DownloadManager 的情况下更新 Android "Downloads"文件夹

android - 如何识别哪个文件触发了 Download_Complete Intent