Programming Tips - Android: Use Storage Access Framework to read/write a tree without re-asking for permission

Date: 2020jul9 OS: Android Keywords: SAF Q. Android: Use Storage Access Framework to read/write a tree without re-asking for permission A. Use intent ACTION_OPEN_DOCUMENT_TREE (available in Android 21+)
public void openDirectory(Uri uriToLoad) { // Choose a directory using the system's file picker. Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); // Provide read access to files and sub-directories in the user-selected // directory. intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Optionally, specify a URI for the directory that should be opened in // the system file picker when it loads. intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uriToLoad); startActivityForResult(intent, your-request-code); }
Source: https://developer.android.com/training/data-storage/shared/documents-files#java From a reddit AMA with actual Google personal which confirms you don't have to re-ask: Roxanna Aliabadi: You can request a user's access to a specific directory using ACTION_OPEN_DOCUMENT_TREE, then your app will be able to read and write to that directory as much as you need to without asking for permission each time. https://www.reddit.com/r/androiddev/comments/hk3hrq/were_on_the_android_engineering_team_ask_us/fwqj0yp/?context=3