Android Share Image File Intent

July 25, 2018
using FileProvider

Share image file by intent

val shareFile: File = ...

val uri = FileProvider.getUriForFile(activity, "${BuildConfig.APPLICATION_ID}.fileprovider", shareFile)
ShareCompat.IntentBuilder
        .from(activity)
        .setType("image/*")
        .setChooserTitle("Share Photo")
        .addStream(uri)
        .startChooser()

NOTE: if you didn’t setup FileProvider property, you will bump into error lile java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.luasoftware.package_name/dir/FILENAME.jpg

Setup FileProvider

Edit AndroidManifest.xml.

<manifest ...>

    <application ...>

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
        ...
    </application>
</manifest>

Create res/xml/file_paths.xml (specify location of files).

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Pictures/PixPin" />
    <cache-path name="my_cache" path="." />
</paths>

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.