5

I am using the below code to create a directory/ file in storage.

   File file  = new File(Environment.getExternalStorageDirectory().toString(), "/MyDirectory");

After updating target SDK version 29 in android 10 its not woking.

can anyone suggest how to create a folder outside the application scope?

Parth
  • 1,908
  • 1
  • 19
  • 37

1 Answers1

-3

For Android version 10:

https://stackoverflow.com/a/58379655/3811983


For Android versions below Android 10: (including this here as no one develops only for Android 10. This will make it a complete answer for anyone looking for including this functionality in their apps)

Here are the steps that I followed, and are working for me:

  • Include the following permission in your app's AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  • Since WRITE_EXTERNAL_STORAGE is dangerous permission, at app runtime, check if the app has this permission, if not, request the user to grant it.

Doc1 Doc2 AirPermissions (A lightweight library to simplify Android Runtime Permissions)

  • Check if external storage is present and the app can read and write to it
if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
     // further code here
}
  • If everything is right, you can proceed to create your public directory:
val rootFile = android.os.Environment.getExternalStorageDirectory()
val appRootFolder = File(rootFile.absolutePath + "/MyDirectory")
if (appRootFolder.exists() && appRootFolder.isDirectory) {
     // proceed
} else {
     val wasAppRootFolderCreated = appRootFolder.mkdirs()
     if (wasAppRootFolderCreated) {
          // proceed
     } else {
          // error: could not create the folder
     }
}
mumayank
  • 1,670
  • 2
  • 21
  • 34
  • 2
    This does not work on Android 10 (by default) and Android R+ (for all apps). The question specifically was about Android 10. – CommonsWare Oct 15 '19 at 10:53