FileProvider
FileProvider is part of AndroidXCoreLibrary. FileProvider handles file sharing from one app to another app. FileProvider component generates content URIs for files based on declaration in xml file. Here we will see how to add FileProvider in app.
Create File Paths
Create a new file in res/xml folder with name filepaths.xml. We need to specify directories used by our app in the file by xml element. Here is sample code for the filepaths:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
Within paths tag we can use <file-paths>, <external-path> and other tags to define paths for each type of directory and file.
<file-paths>
Shares directory within the files/ directory of the app’s internal storage
<external-path>
Shares directories in external storage
<cache-path>
element to share directories in your internal cache directory
Specify FileProvider
We have defined how our internal and external storage directories will look like, now we can define our FileProvider with paths within the Manifest.xml file.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
...>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.myapp.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
...
</application>
</manifest>
Let’s understood properties of provider
android:authorities
This attribute specifies the URI authority that you want to use for content URIs granted by the FileProvider. Generally value for this attribute is APP_PACKAGE_NAME + . + fileprovider
<meta-data>
This element specifies paths which we create in our last step.
We are ready to test app now. We can define path for each type of directory.
Hope you have gain some knowledge.
Let me know you feedback.
You can also request my new demo for any topic, I will be happy to provide it.
Thank you.