Open In App

How to Share Image of Your App with Another App in Android?

Last Updated : 23 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Most of the time while using an app we want to share images from the app to another app. While using Many Social Media Platforms we find this feature to be very useful when we want to share information from one app to another. The Android Intent resolver is used when sending data to another app as part of a well-defined task flow. To use the Android intent resolver, create an intent and add extras. Here we are going to understand how to do that.

Note: If you want to share the Text of Your App with Another App in Android then please refer to this.

Step by Step Implementation

Step 1: Create a new Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.  

Step 2: Working with the AndroidManifest.xml file

Add the following permission to the AndroidManifest.xml file

<uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE” />

<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />

Add the following lines inside the <application> tag and after the </activity> tag.

XML




<provider
  android:name="androidx.core.content.FileProvider"
   
  <!-- Write down your package name -->
  android:authorities="com.anni.shareimage.fileprovider"
 
  android:exported="false"
  android:grantUriPermissions="true">
    <!-- we intend to request content
          URIs for the images/subdirectory
          of your private file area -->
    <meta-data
      android:name="android.support.FILE_PROVIDER_PATHS"
      android:resource="@xml/paths" />
</provider>


Below is the complete code for the AndroidManifest.xml file

XML




<?xml version="1.0" encoding="utf-8"?>
    package="com.anni.shareimage">
 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ViewPdfActivity"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.anni.shareimage.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/paths" />
        </provider>
    </application>
 
</manifest>


Step 3: Create a new XML file

Create an XML directory in res and then create a paths.xml file in it. A file Provider can only generate a content URI for files in directories that we specify beforehand. We specify a directory, specify its storage area and path in XML, using child elements of the <paths> element. Below is the video of creating the XML file.

XML




<?xml version="1.0" encoding="utf-8"?>
<paths>
    <cache-path
        name="shared_images"
        path="images/" />
</paths>


Step 4: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.

Reference article: How to Add Image to Drawable Folder in Android Studio?

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!-- Here we will attach our image to share -->
    <ImageView
        android:id="@+id/shareimage"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:src="@drawable/image" />
 
    <!-- We will click on it then shareonlytext
         function will be called-->
    <Button
        android:id="@+id/share"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@color/colorPrimary"
        android:padding="10dp"
        android:text="Click here to Share "
        android:textSize="10dp" />
     
</LinearLayout>


Step 5: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
 
import java.io.File;
import java.io.FileOutputStream;
 
public class MainActivity extends AppCompatActivity {
 
    Button share;
    ImageView imageView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        share = findViewById(R.id.share);
        imageView = findViewById(R.id.shareimage);
 
        // initialising text field where we will enter data
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Now share image function will be called
                // here we  will be passing the text to share
                // Getting drawable value from image
                BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getDrawable();
                Bitmap bitmap = bitmapDrawable.getBitmap();
                shareImageandText(bitmap);
            }
        });
    }
 
    private void shareImageandText(Bitmap bitmap) {
        Uri uri = getmageToShare(bitmap);
        Intent intent = new Intent(Intent.ACTION_SEND);
 
        // putting uri of image to be shared
        intent.putExtra(Intent.EXTRA_STREAM, uri);
 
        // adding text to share
        intent.putExtra(Intent.EXTRA_TEXT, "Sharing Image");
 
        // Add subject Here
        intent.putExtra(Intent.EXTRA_SUBJECT, "Subject Here");
 
        // setting type to image
        intent.setType("image/png");
 
        // calling startactivity() to share
        startActivity(Intent.createChooser(intent, "Share Via"));
    }
 
    // Retrieving the url to share
    private Uri getmageToShare(Bitmap bitmap) {
        File imagefolder = new File(getCacheDir(), "images");
        Uri uri = null;
        try {
            imagefolder.mkdirs();
            File file = new File(imagefolder, "shared_image.png");
            FileOutputStream outputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, outputStream);
            outputStream.flush();
            outputStream.close();
            uri = FileProvider.getUriForFile(this, "com.anni.shareimage.fileprovider", file);
        } catch (Exception e) {
            Toast.makeText(this, "" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
        return uri;
    }
}


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads