无法获取 Environment.DIRECTORY_DOWNLOADS 的外部存储文件目录

问题描述

在应用程序中,我已经实现了下载管理器来下载新的应用程序版本(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 权限。

解决方法

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...