Search code examples
javaandroidimagetextshare

Share text and image at the same time in Android


I've been trying for several hours to share both text & image (at the same time) with Intent.ACTION_SEND. And despite all my attempts to make it work, I'm still not able to do it.

I've searched all over Google and it may be strange, but I only found 2 posts that talk about how to share text & image at the same time, I tried them out however none of them worked. I tried using a method and here's what I ended up with:

Uri imageToShare = Uri.parse("android.resource://com.example.application/drawable/invite"); //Image to be shared
String textToShare = "Text to be shared"; //Text to be shared

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, textToShare);
shareIntent.setType("*/*");
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_TEXT, imageToShare);
startActivity(Intent.createChooser(shareIntent, "Share with"));
  • The code above shows an error message "Sharing failed, please try again."
  • The image I want to send is invite.png and it's located in the drawable folder.
  • I'm using a phone with Android O (8.0).

I hope the above information will be useful. I'm still a beginner in Java and any help would be greatly appreciated!


Solution

  • I finally managed to do it in a simpler way! I created a base64 from the image and added it as a string in the strings.xml file (make sure to remove data:image/png;base64, from the start of the string).

    The code I used is the following:

    byte[] decodedString = Base64.decode(getString(R.string.share_image), Base64.DEFAULT); //The string is named share_image.
    Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    Uri imageToShare = Uri.parse(MediaStore.Images.Media.insertImage(MainActivity.this.getContentResolver(), decodedByte, "Share image", null)); //MainActivity.this is the context in my app.
    String textToShare = "Sample text"; //Text to be shared
    
    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/*");
    share.putExtra(Intent.EXTRA_TEXT, textToShare);
    share.putExtra(Intent.EXTRA_STREAM, imageToShare);
    startActivity(Intent.createChooser(share, "Share with"));
    

    I hope this answer will solve many peoples issues!

    Thanks a lot for @notyou & @CommonsWare