How to open a file from shared storage using the NDK in Android 11

Viewed 1033

The permissions for accessing shared storage (/storage/emulated/0) are getting really really complicated and changing all the time. As I understand it when targeting Android 11 there is no way to opt out of scoped storage, which means you literally can't ever do fopen("/storage/emulated/0/foo.dat");. Apparently the preferred way to open a file will be with the ACTION_OPEN_DOCUMENT but this just returns a content:// URI, which I can't read using the NDK. I'm also unsure if you get to use that URI forever.

How are NDK libraries meant to access files in /storage/emulated/0 on Android 11?

2 Answers

Aha, it seems they have moved the permission to read/write all files to MANAGE_EXTERNAL_STORAGE. It's one of those permissions that users have to grant in settings, and there's an intent (ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION) to take people directly there.

However they probably won't let you upload an app to the play store with this permission unless it's a file manager or similar, and you currently can't use it at all.

If your app includes a use case that's similar to the following examples, it's likely to be allowed to request the MANAGE_EXTERNAL_STORAGE permission:

  • File managers
  • Backup and restore
  • Anti-virus apps
  • Document management apps

Due to COVID-19 related considerations, apps that target Android 11 (API level 30) or higher and need the MANAGE_EXTERNAL_STORAGE permission cannot be uploaded to Google Play until early 2021.

I should also note that there seems to be an exception for opening media files only - i.e. files indexed by Android's media scanner.

On Android 11 devices:

All apps can write files in all the public directories like Dowload, Documents, DCIM, Pictures and so on.

If not in the directory itself then in a subdirectory of it which you create first.

For DCIM and Pictures only files with extension like .jpg, .png and .webp are accepted.

More public directories only accept certain extensions.

Related