【问题标题】:DownloadManager Failed to create target file / E/cutils:|Failed to mkdirat | Failed to ensure directory |SDK<21DownloadManager 无法创建目标文件/E/cutils:|无法创建 mkdirat |无法确保目录 |SDK<21
【发布时间】:2021-02-28 12:11:15
【问题描述】:

我正在使用以下代码通过 DownloadManager 下载文件。下载可在 SDK 21+ 的真实设备和模拟器上完美运行。

但是,在具有 SDK 19 及以下版本的真实设备和模拟器上,下载失败并在 Logcat 中出现以下错误:

三星设备:

E/cutils: Failed to mkdirat(/storage/extSdCard/Android): Read-only file system

W/ContextImpl: Failed to ensure directory: /storage/extSdCard/Android/data/com.example.downloadcatalogues/files

I/DownloadManager: Download 71 finished with status FILE_ERROR

模拟器:

W/DownloadManager: Failed to create target file /storage/sdcard/Android/data/com.example.downloadcatalogues/files/test/123.zip

I/DownloadManager: Download 71 finished with status FILE_ERROR

如果我将位置更改为 Environment.getExternalStorageDirectory(),我会得到相同的行为。

清单

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
        android:usesCleartextTraffic="true"
</application>

活动

findViewById(R.id.extrauma_button).setOnClickListener(v -> {
            String urlZipFile = "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-large-zip-file.zip";
            downloadPro(urlZipFile, "extrauma");
            });

private void downloadPro(String url, String title){
        DownloadManager downloadManager;

    try{
        File file = new File(getApplicationContext().getExternalFilesDir(null).getAbsolutePath()+"/test/","123.zip");

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url))
            .setTitle(title)
            .setDescription("Downloading")Notification
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
            .setDestinationUri(Uri.fromFile(file))
           .setRequiresCharging(false)
            .setAllowedOverMetered(true)
            .setAllowedOverRoaming(true);

    downloadManager = (DownloadManager) getApplicationContext().getSystemService(DOWNLOAD_SERVICE);
    long downloadID = downloadManager.enqueue(request);
    Log.v("downloadProId", downloadID+"");
}
catch (Exception e){
    Log.w("stopped", e.toString());
}
}

注意: 如果我在 SDK 19 及更低版本的设备上的 Chrome 浏览器上尝试下载链接,则下载链接有效!

我是不是错过了什么?

【问题讨论】:

    标签: android android-file android-download-manager android-external-storage android-storage


    【解决方案1】:

    我能够通过以下方式解决问题:

    .setDestinationInExternalFilesDir(getApplicationContext(),"test","123.zip")
    

    代替:

    .setDestinationUri(Uri.fromFile(file))
    

    由于某种原因,.setDestinationUri 方法不适用于棒棒糖之前的版本。

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多