[英]Android Oreo (API 26) - Create dir in external storage
I've been developing an app on nougat that creates a directory in the external storage. 我一直在nougat上开发一个应用程序,它在外部存储中创建一个目录。
I used to do it like this: 我过去常常这样做:
final File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Chords/Processed Audio");
dir.mkdirs();
This code does not seem to work on API 26 (Android Oreo). 此代码似乎不适用于API 26(Android Oreo)。 The directory is not created.
目录未创建。
How can I achieve the same thing, preferably that works on all android version from API 21 to API 26? 我怎样才能实现相同的功能,最好适用于从API 21到API 26的所有Android版本?
I have no problems running your existing code on a Nexus 5X running Android 8.0. 在运行Android 8.0的Nexus 5X上运行现有代码没有问题。 Using
adb shell ls /storage/emulated/0
, I see Chores/
, and inside there I see Processed Audio/
. 使用
adb shell ls /storage/emulated/0
,我看到Chores/
,在里面我看到Processed Audio/
。 This is for an app with WRITE_EXTERNAL_STORAGE
permission, including runtime permissions. 这适用于具有
WRITE_EXTERNAL_STORAGE
权限的应用程序,包括运行时权限。
That being said, ideally, do not use string concatenation to create File
objects. 理所当然地说,不要使用字符串连接来创建
File
对象。 Instead, use: 相反,使用:
final File dir = new File(new File(Environment.getExternalStorageDirectory(), "Chords"), "Processed Audio");
@Daniele,请参阅https://stackoverflow.com/a/44455957/966789和https://stackoverflow.com/a/33031091/966789(Android为Android 6.0添加了新的权限模型(Marshmallow)。如果你的targetSdkVersion> = 23如果您在Marshmallow(或更高版本)设备上运行,则可能需要启用运行时权限。您还应该阅读有关运行时权限更改的更多信息。如果您使用的是targetSdkVersion> = 24,则还必须将FileProvider配置为show in以下示例使用com.codepath.fileprovider并且应该与指定的权限XML标记匹配)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.