Android Share Image File Intent

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 ...>

        <!-- android:name="android.support.v4.content.FileProvider" -->
        <provider
            android:name="androidx.core.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="images" />
    <cache-path name="my_cache" path="." />
</paths>

NOTE: Use cache-path if files are store in cache dir, else use external-path. Use . if you uncertain of the exact directory name.

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.