Setup FileProvider
by editing AndroidManifest.xml
<manifest ...>
...
<application ...>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.myapp.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
...
</application>
</manifest>
Specify sharable directories by editing res/xml/file_paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!-- everything -->
<cache-path name="all" path="." />
<!--
<cache-path name="images" path="/images" />
-->
</path>
Create intent to send/share file.
val uri = FileProvider.getUriForFile(context, "com.mydomain.myapp.fileprovider", outputFile)val shareIntent = Intent(Intent.ACTION_SEND)shareIntent.type = "application/octet-stream"// intent.type = "image/jpeg"shareIntent.putExtra(Intent.EXTRA_STREAM, uri)startActivityForResult(Intent.createChooser(shareIntent., "Backup"), BACKUP_FILE_REQUEST_CODE)
NOTE: I believe it's not possible to share database file as you will get IllegalArgumentException: Failed to find configured root that contains /data/data/com.mydomain.myapp/databases/*
. The solution to copy the database file to cache directory before sharing.
Check if intent is successful or fail.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == BACKUP_FILE_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // success } else if (resultCode == Activity.RESULT_CANCELLED) { // cancelled } }}
References: