But I Need a File!!!

Not everything can work with a Uri:

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:


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.