Android Intent To Send And Share File

Apr 14, 2018

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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.