Android API 21 introduced new framework called SAF (Storage Access Framework) for receiving access to storage. After API 30 this is single possible solution for getting access to external storage by your app.
I am faced with 2 bugs (?) in that framework when using ACTION_OPEN_DOCUMENT_TREE intent.
- After user grants access to required folder to the app, provided Uri becomes initial location for all next calls of this intent, DocumentsContract.EXTRA_INITIAL_URI is totally ignored.
- Button "USE THIS FOLDER" is hidden for the initial folder in all next calls of this intent. For selecting the same folder user needs to go up to the parent directory, after that go back and only in this case button will appear.
Does anybody have the same problems?
My code:
public void openDirectory() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, "content://com.android.externalstorage.documents/tree/2C13-1335%3AMusic");
startActivityForResult(intent, FOLDER_ACCESS_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FOLDER_ACCESS_REQUEST_CODE && resultCode == RESULT_OK) {
if (data != null) {
Uri uri = data.getData(); // there i receive uri of selected folder, it is "content://com.android.externalstorage.documents/tree/2C13-1335%3AMusic"
getContentResolver().takePersistableUriPermission(uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION |
Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
}
With this code both bugs are present. If instead of
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, "content://com.android.externalstorage.documents/tree/2C13-1335%3AMusic");
I write
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, "content://com.android.externalstorage.documents/document/primary:");
Expolorer is opened at internal storage and button is visible, i.e. both bugs are absent. And if i write
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, "content://com.android.externalstorage.documents/document/secondary:");
Explorer is opened at cached (i.e. last selected) folder, but button is present, so i have only 1st bug