How to Share Image of Your App with Another App in Android
🔥 Key Points Covered:
- How to share images from one Android app to another.
- Using the Android Share menu effectively.
- A detailed walk-through for various apps and scenarios.
- Tips and tricks to make sharing smoother.
paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path
name="shared_images"
path="images/"/>
</paths>
Add this in AndroidManifest.xml inside the application tag
<provider
android:authorities="com.bdtopcoder.imagesharing"
android:name="androidx.core.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true"
>
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/paths"
/>
</provider>
Storage Permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Add this to method in public class in your activity MainActivity.java
private void shareImageAndText(Bitmap bitmap){
Uri uri = getImageToShare(bitmap);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,uri);
intent.putExtra(Intent.EXTRA_TEXT,"Sharing Images");
intent.putExtra(Intent.EXTRA_SUBJECT,"Subject");
intent.setType("image/png");
startActivity(Intent.createChooser(intent,"Share via"));
}
private Uri getImageToShare (Bitmap bitmap){
File imageFolder = new File(getCacheDir(),"images");
Uri uri = null;
try {
imageFolder.mkdir();
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(MainActivity.this,"com.bdtopcoder.imagesharing", file);
} catch (Exception e){
Toast.makeText(this, "Exception: "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
return uri;
}
Button setOnClickListener code:
button.setOnClickListener(view -> {
BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
shareImageAndText(bitmap);
});