But I Need a File
!!!
Not everything can work with a Uri
:
- Some libraries insist on files, possibly for the ability to randomly read (or perhaps write) to locations in the file, or to be able to start over reading the file from the beginning
- Some framework classes, like those for SQLite, can only work with files
- The NDK has no direct ability to work with
Uri
values - And so on
Unfortunately, with the external storage restrictions placed on external storage, your options are very limited here.
Option #1: See if the API Supports File-Like Stuff
If the API you are using supports InputStream
or FileDescriptor
, you can use those with a Uri
pointing to content… probably. Not all content Uri
values necessarily support FileDescriptor
. You can get an InputStream
or FileDescriptor
on your content via ContentResolver
.
Similarly, some NDK code can work with file descriptors.
Option #2: Ask User to Put in App-Specific Location
You can ask the user to place the file in your app-specific directories on external or removable storage. If you are using methods like getExternalFilesDir()
on Context
, you would ask the users to put the files in locations inside Android/data/.../
(where ...
is your application ID). Note, though, that these directories may not exist initially — be sure to create the directory first before expecting the user to use it.
As noted above, this will be aggravating for the user. Partly, that is because the directory structure is not very user-friendly, particularly given the long list of application IDs on many devices. It also may make it more difficult for the user to also use this file with other apps.
Option #3: Copy Stream to Local File
Otherwise, if you get a Uri
from something like the Storage Access Framework, you are left with the unappetizing option of copying that content to some file that you control (e.g., on internal storage), then using that file.
On the plus side, you control your copy of the content and can manipulate it however you wish.
However, there are costs:
- The copy may take a while, for larger files
- You use additional storage space for the copy
- If you modify the copy, the only way that the user gets those modifications is through your app or if you copy the data back out to some
Uri
-identified content - Depending on your use case for file, you might not know when a good time is to remove your copy (e.g., you use
FileProvider
to give access to some other app)
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.