I would like to make a file manager app targeting API level 31 that requires access to all files on the device. To do this, I have followed the guidance here: https://developer.android.com/training/data-storage/manage-all-files.
I have added the MANAGE_EXTERNAL_STORAGE permission and allowed it in the device settings. Here is the Kotlin code I'm using to list the root directories on the device:
val file = Environment.getStorageDirectory()
// ensure we have file access permission
if (Environment.isExternalStorageManager() && Environment.isExternalStorageManager(file)) {
Log.d("FileManager", "Exists: ${file.exists()}")
Log.d("FileManager", "Is directory: ${file.isDirectory}")
Log.d("FileManager", "List files: ${file.listFiles()}")
}
Here is the output:
D/FileManager: Exists: true
D/FileManager: Is directory: true
D/FileManager: List files: null
As you can see, the directory exists, but listFiles()
unexpectedly returns null
. Given this, how can I navigate all the files on the device, starting from the root directory?
I have seen similar questions, but their answers all seem outdated or unusable. Here are some of the suggestions I've found:
Environment.getExternalStorageDirectory()
android:requestLegacyExternalStorage="true"
ActivityResultContracts
Given this, how can I navigate all the files on the device, starting from the root directory?
You can't, at least on unrooted devices. Even with MANAGE_EXTERNAL_STORAGE
, all that you have access to is external storage, not the entire device filesystem.
Use
Environment.getExternalStorageDirectory()
— This works, but is deprecated in API level 31.
It is now undeprecated, as of Android 12L and Android 13 DP2. Hopefully the public documentation will reflect this when Android 13 ships later this year.
Use android:requestLegacyExternalStorage="true" — This is outdated.
You still want it for Android 10 support.