【问题标题】:Failed to get external storage files directory for Environment.DIRECTORY_DOWNLOADS无法获取 Environment.DIRECTORY_DOWNLOADS 的外部存储文件目录
【发布时间】:2021-02-12 10:10:02
【问题描述】:

在应用程序中,我实现了下载管理器来下载新的应用程序版本(APK 文件)然后安装它。我最近迁移到范围存储以使用应用程序的私有外部目录。这是代码:

private void setupDownloadRequest() {
    mDownloadRequest = new DownloadManager.Request(Uri.parse(mDownloadUrl));
    mDownloadRequest.setTitle(mFileName);
    mDownloadRequest
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    mDownloadRequest.setMimeType(getMimeType());
    mDownloadRequest.setDestinationInExternalFilesDir(mActivity, Environment.DIRECTORY_DOWNLOADS, mFileName);
}

该过程在 Android

Fatal Exception: java.lang.IllegalStateException: Failed to get external storage files directory
    at android.app.DownloadManager$Request.setDestinationInExternalFilesDir(DownloadManager.java:782)
    ...

查看Android SDK(API 29)中的代码,目录好像不见了:

public Request setDestinationInExternalFilesDir(Context context, String dirType,
        String subPath) {
    final File file = context.getExternalFilesDir(dirType);
    if (file == null) {
        throw new IllegalStateException("Failed to get external storage files directory");
    ...

您知道如何解决这个问题吗? Environment.DIRECTORY_DOWNLOADS在某些设备上是否缺少目录,不应该自动创建吗?

在下载之前,我检查了Manifest.permission.WRITE_EXTERNAL_STORAGE的权限是否被授予。

【问题讨论】:

  • getExternalFilesDir(null) 的路径应该自动存在,但 getExternalFilesDir("Download") 不存在。但是如果你调用这个函数,它可能会被创建。如果没有,请自己创建它。这是一个奇怪的故事,因为我发现 DownloadManager 总是创建不存在的目录
  • String dirType 那真的叫类型吗?多么混乱!它仅用作子文件夹的名称。
  • 我明白了,所以getExternalFilesDir(null) 应该指向应用程序外部存储的根目录?如果这能解决问题,我可以这样做。
  • 是的名字dirType是相当令人不安的!
  • 为什么不使用 MediaStore 将文件保存到 API 29+ 的 Download 中?

标签: android scoped-storage


【解决方案1】:

在 Android 10 设备的清单应用程序标签中添加 android:requestLegacyExternalStorage="true"

【讨论】:

  • 对于像 getExternalFilesDir() 这样的应用程序特定目录,这没有帮助,也永远不需要。
  • 是的,如果我理解得很好,requestLegacyExternalStorage 用于公共外部目录(我有特定于应用程序的外部目录),并且此标志将在 Android 11 上被忽略
  • 我在没有这个标志的 Android 10 模拟器上也没有问题。
猜你喜欢
  • 1970-01-01
  • 2016-07-31
  • 2016-10-23
  • 2013-03-08
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多