Android Oreo (API 26) - Create dir in external sto

2019-06-20 22:19发布

问题:

I've been developing an app on nougat that creates a directory in the external storage.

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). 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?

回答1:

I have no problems running your existing code on a Nexus 5X running Android 8.0. Using adb shell ls /storage/emulated/0, I see Chores/, and inside there I see Processed Audio/. This is for an app with WRITE_EXTERNAL_STORAGE permission, including runtime permissions.

That being said, ideally, do not use string concatenation to create File objects. Instead, use:

final File dir = new File(new File(Environment.getExternalStorageDirectory(), "Chords"), "Processed Audio");


回答2:

@Daniele, see https://stackoverflow.com/a/44455957/966789 and https://stackoverflow.com/a/33031091/966789 (Android added new permission model for Android 6.0 (Marshmallow). If your targetSdkVersion >= 23 and you are running on a Marshmallow (or later) device, you may need to enable runtime permissions. You should also read more about the runtime permissions changes. If you are using targetSdkVersion >= 24, you also must configure a FileProvider as show in this section. The example below uses com.codepath.fileprovider and should match the authorities XML tag specified)