cooldev
cooldev

Reputation: 419

What is the better way of using Storage Access Framework Output URI File than DocumentFile in Android 10?

From Android 11 onwards (API > 29), Environment.getexternalstoragedirectory() will no more work. Since most of the libraries are using java.io.file parameter: Is it possible to get a regular File from DocumentFile? We will have to use DocumentFile. But since it's slow, I've found over the top solution here: https://www.reddit.com/r/androiddev/comments/725ee3/documentfile_is_dead_slow_heres/

Is there any other way so that we can use the old functions of java.io.file from Android 11 onwards? How can we use Document Since they have provided Environment.getexternalstoragedirectory() support only Till Android Q/ Android 10 by adding android:requestLegacyExternalStorage="true" in application tag. I would like to know the best way to handle files. Possibly, the one which will be compatible with old java.io.file and will require to write less code.

To open Folder picker:

Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        startActivityForResult(Intent.createChooser(i, "Choose Directory"), OPEN_DIRECTORY_REQUEST_CODE);

OnActivityResult:

getContentResolver().takePersistableUriPermission(
                       data.getData(),
                       Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION
               );
DocumentFile documentFile = DocumentFile.fromTreeUri(this, data.getdata);

FileNotFound if I try get file using Environment.getexternalstoragedirectory()

Upvotes: 2

Views: 737

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006584

Since most of the libraries are using java.io.file parameter

Hopefully, most of those libraries will be rewritten to support other data sources.

Is there any other way so that we can use the old functions of java.io.file from Android 11 onwards?

Limit yourself to the portions of the filesystem for which you have read/write access via methods on Context:

  • getFilesDir()
  • getCacheDir()
  • getExternalFilesDir() and getExternalFilesDirs()
  • getExternalCacheDir() and getExternalCacheDirs()
  • getExternalMediaDir() and getExternalMediaDirs()

For those directory trees, you can use File.

Otherwise, in general, you treat the rest of the device no different than you would treat the Web: get an InputStream and "download" the content.

Upvotes: 4

Related Questions