When you need to share a file with other apps, the easiest way could be to use the external storage as a temporary place where to save this file. For example, if you need to take a picture with a camera app, you need to specify a file where the camera app will save the picture, and using external storage might be tempting.
However this solution has many drawbacks:
Because you put your file in a public directory, you can’t safely delete it nor control which app can read and modify it.
This could make many users afraid and may lead to a bad UX with runtime permissions.
Since you can’t safely delete your shared files, you let them in the external storage forever.
You may already use
ContentProvider to share data with other apps, you can do the same with
FileProvider to share files!
FileProvider is part of Support Library, available for all Android versions starting 2.3.
The main goal of this API is to temporary open a private file to some targeted apps: you keep the file in your private folder, and let some other apps read or even write it via a secured
ContentProvider. Permissions are revoked when your activity is destroyed.
In your app
build.gradle, add this dependency:
Create an xml file (for example
xml resources folder:
ApplicationManifest.xml, add this provider inside
Just set your
com.drivy.android.myfileprovider, and link the created xml resource file in
android:authorities to automatically use your package name:
First thing to do: get the shared file’s Uri
Use the same provider authority as in your
The Uri will looks like this:
You can now create a chooser intent:
And start it:
You need to manually grant permission for older Android versions.
Before sharing your file, you’ll have to manually grant the permission (read and/or write), for all applications targeted with your intent. Indeed, you can’t know which one the user will choose to share the file with.
We can assume that, when returning back to your app and leaving the activity, the shared file has already been copied by the targeted app, and is not required anymore. You can revoke all permissions.
FileProvider is a really convenient and elegant way to get rid of
WRITE_EXTERNAL_STORAGE, I encourage you to use it: your app will be better without extra permissions.