Share Intent For a Bitmap Without Saving a File

SHARE-INTENT-FOR-A-BITMAP-WITHOUT-SAVING-A-FILE-1.png

5th February, 2023

Hi Android Developer, When you don’t want to save the bitmap permanently to the user phone and just want to share it. I’m going to show you how you can export a bitmap without saving the file. Indeed, the bitmap will be saved in the cache directory.

Step 1: Setup File Provider

FileProvider is subclass of ContentProvider which allows sharing of files between application through content:// URI instead of file:// URI. Create a file in XML folder (create XML folder if you didn’t have) and add code as follows.

Project ⇒ app ⇒ src ⇒ main ⇒ res ⇒ xml ⇒

file-provider-XML
provider_path.xml in Project
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-cache-path name="external_files" path="my_images/"/>
</paths>

Open AndroidManifest.xml file and add file provider before </application> tag.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.codestringz.mytestapp">

    <application
        ...
		...>
        <activity
			...
			.../>
        <activity
			...
			.../>
			
		<!--File Provider-->
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
		
    </application>

</manifest>

Step 2: Share Bitmap

After setting the File Provider, You have to create a bitmap and share it through the Intent class. Open the Activity and add the code as follows.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="www.CodestringZ.com" />

    <Button
        android:id="@+id/shareButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Share Bitmap" />

</RelativeLayout>
package com.codestringz.mytestapp;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

public class MainActivity extends AppCompatActivity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //set UI References
        setUIRef();
    }

    private void setUIRef()
    {
        Button shareButton = findViewById(R.id.shareButton);
        shareButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //Here I am creating a bitmap from the application icon
                Bitmap bitmap = BitmapFactory.decodeResource(MainActivity.this.getResources(), R.mipmap.ic_launcher);
                shareBitmap(bitmap);
            }
        });
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    private void shareBitmap(@NonNull Bitmap bitmap)
    {
        //---Save bitmap to external cache directory---//
        //get cache directory
        File cachePath = new File(getExternalCacheDir(), "my_images/");
        cachePath.mkdirs();

        //create png file
        File file = new File(cachePath, "Image_123.png");
        FileOutputStream fileOutputStream;
        try
        {
            fileOutputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();

        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        //---Share File---//
        //get file uri
        Uri myImageFileUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", file);

        //create a intent
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra(Intent.EXTRA_STREAM, myImageFileUri);
        intent.setType("image/png");
        startActivity(Intent.createChooser(intent, "Share with"));
    }
}

Happy coding!

Leave a Reply