1

我使用 DownloadManager 下载文件并从 DownloadManager.COLUMN_LOCAL_URI 中获取它们的名称。下载同一个文件超过 11 次。11 次后开始怀疑奇怪的名字。例子:

文本.txt

text-1.txt

text-2.txt

text-3.txt

text-4.txt

text-5.txt

text-6.txt

text-7.txt

text-8.txt

text-9.txt

text-10.txt

text-26.txt

text-14.txt

可能是什么问题呢?

先感谢您

编辑:

带上我的代码

public static long downloadFile(Context ctx, String url, String title, String description, String filename, String mimetype, BroadcastReceiver onDownloadComplete) {
        DownloadManager dm = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);

        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();
        long res = dm.enqueue(new DownloadManager.Request(Uri.parse(url)).setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI).setAllowedOverRoaming(false).setTitle(title).setMimeType(mimetype).setDescription(description).setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename));
        ctx.registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        Toster.showGreenToast(ctx, ctx.getString(R.string.download_started, filename));
        return res;
    }

    public static String getDownloadCompletedFileName(Context ctx, Intent intent) {
        String res = "";

        try {
            Bundle extras = intent.getExtras();
            DownloadManager dm = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);

            DownloadManager.Query q = new DownloadManager.Query();
            q.setFilterById(extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID));
            Cursor c = dm.query(q);

            if (c.moveToFirst()) {
                int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    // process download
                    res = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    // get other required data by changing the constant passed to getColumnIndex
                }
            }

            c.close();
        } catch (Exception e) {}

        return res;
    }
4

2 回答 2

1

请参阅http://developer.android.com/reference/android/app/DownloadManager.html#ERROR_FILE_ALREADY_EXISTS

正如它所说:下载管理器不会覆盖现有文件

正如我所看到的,它不会抛出异常,而是将“-n”附加到文件名的末尾。

于 2014-10-03T12:26:50.617 回答
0

也许您应该使用setDestinationInExternalFilesDir(),setDestinationInExternalPublicDir()或者setDestinationUri()在创建DownloadManager.Request时设置文件名和目录。

于 2014-01-14T21:37:46.127 回答