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
}
}