Android 11 不在外部存储上创建应用程序目录

Android 11 doesn't create app directory on external storage

最近我将我的智能手机更新到 Android11,我注意到我的一个应用程序在外部存储上创建目录时崩溃了。我已阅读 Android 11 份文档,现在是 Starting in Android 11, apps cannot create their own app-specific directory on external storage。很奇怪,因为当我打开 Android/data 目录时,有很多应用程序文件夹,所以有可能这样做,或者可能有应用程序在更新之前创建的文件夹?

好的,我找到了一种方法。我们的应用程序无法创建该文件夹,但如果我们调用 getApplicationContext().getExternalFilesDir(""); Android 将为我们创建该文件夹。

很愚蠢,如果我们想要打开不存在的目录,它会创建它,但是当我们想自己创建它时,就会出现问题。 Android 开发者应该让我们的生活更轻松,但他们每次更新都会让我们的生活变得更加困难。

getApplicationContext().getExternalFilesDir(""); 将为您提供应用程序的特定外部存储目录,其他应用程序将无法访问其内容。正如我所相信的那样,

是什么意思

Starting in Android 11, apps cannot create their own app-specific directory on external storage

除了前面提到的目录外,不能在外部存储上创建其他app-specific目录。 我发现这个 article 有点用。

            ContentValues values = new ContentValues();

            values.put(MediaStore.MediaColumns.DISPLAY_NAME, currentlyDownloadingFileObject.getFileName());
            values.put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4");
            values.put(MediaStore.MediaColumns.BUCKET_DISPLAY_NAME, "my_file.mp4");
            values.put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/" + "YOUR_DIRECTORY_NAME_GOES_HERE");

            context.getApplicationContext().getExternalFilesDir(MediaStore.Video.Media.EXTERNAL_CONTENT_URI+"/"+getApplicationName(context));

            Uri newUri newUri = context.getContentResolver()
                    .insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);

         // values.put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/" + "YOUR_DIRECTORY_NAME_GOES_HERE");

您可以存储在内容值中提供 RELATIVE_PATH 的文件,如果尚未创建目录,它将创建该目录