Home > Enterprise >  How do I navigate the external storage file system in Android 12?
How do I navigate the external storage file system in Android 12?

Time:03-29

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:

  • Use Environment.getExternalStorageDirectory()
    • This works, but is deprecated in API level 31.
  • Use android:requestLegacyExternalStorage="true"
    • This is outdated.
  • Use ActivityResultContracts
    • This does not apply to a custom file manager app.

CodePudding user response:

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.

CodePudding user response:

Adding a uses permission MANAGE_EXTERNAL_STORAGE to manifest file is not enough to get 'all files access'.

You also at runtime have to start an intent for Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION.

  • Related