Reputation: 3104
Due to Android 11 and scoped storage I have to start work with Storage Access Framework (SAF), but I have lot of source code that works with File API
. Question 1: Do I have to rewrite everything to work with DocumentFile
?
Pseudo use case:
User creates and picks own directory and system returns Uri
:
//Start pick a directory
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
startActivityForResult(intent, requestCode)
...
onActivityResult {
//check requestCode + resultCode
...
//get Uri
val selectedDir = data.getData();
if (selectedDir == null) {
return;
}
//take persist permission for later use
getContentResolver().takePersistableUriPermission(selectedDir, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
Now I have Uri
of folder selected by user with read/write persistable permissions.
From Android doc
To help your app work more smoothly with third-party media libraries, Android 11 allows you to use APIs other than the MediaStore API to access media files from shared storage using direct file paths. These APIs include the following:
The File API.
Native libraries, such as fopen().
Question 2: well, how can I use File API
, when I have a Uri
from ACTION_OPEN_DOCUMENT_TREE
?
Question 3: does this mean I have to duplicate all the code to work up to Android 9 (or 10 with requestLegacyExternalStorage
) with the File API
and from Android 11+ with the SAF
and Uri
?
Goal is: keep the code with the File API
, but get read/write permissions to the user selected directory.
UPDATE
After the huge testing DocumentFile
is not applicable in practice. Maybe only for a few files.
DocumentFile
creates unnecessarily complicated source code and it's very sloooow related topic.
For example creating of 1000 directories during via File API
~350ms and via DocumentFile
~2300ms. Delete and check if file exist are always very slowly.
From Scoped Storage Recap
Awesome! It would be really great to have some kind of support library or Androidx lib for file handling.
and answer from Google developer is:
We're exploring this option as an experiment, stay tuned 😉
Upvotes: 4
Views: 1725
Reputation: 542
Note that startActivityForResult() is deprecated. Instead registerForActivityResult() shall be used. Unfortunately I have not find any usable Java example for this mechanism, yet. Even Google's example code is still using the deprecated function. I would be glad for any hint.
PS: There is also some ActivityResultContracts.OpenDocumentTree() function that might be helpful, but I also could not find an example how to use it.
Upvotes: 1