Search code examples
androiduriandroid-5.0-lollipopfile-permissions

How to request permission to write to removable sd card in Android 5.0 and above


A simple question. By default android doesn't allow 3rd party apps to write to removable sd card.

But in Android 5.0 I can request for permission to write to removable sdcard and write any file in that directory.

So how to do that? I need an output stream to write to the file.


Solution

  • I can request for permission to write to external sdcard and write any file in that directory.

    Not really.

    On Android 4.4+, you can use getExternalFilesDirs(), getExternalCacheDirs(), and getExternalMediaDirs(). If those return 2+ items, the second and subsequent ones will be locations on removable storage.

    On Android 5.0+, you can use ACTION_OPEN_DOCUMENT_TREE, to ask the user to grant you access to a document tree. That could be the root of removable storage... or anything else the user wants to use. This gives you a Uri back, which you can use with DocumentFile and the rest of the Storage Access Framework. It does not give you filesystem access (e.g., via File).

    On Android 7.0+, you can use StorageManager and StorageVolume to ask for access to a removable storage volume. Once again, though, you get a Uri back to use with DocumentFile, ContentResolver, etc -- you do not get filesystem access.