11

I am creating a file in the cache directory that I'd like to share with others (via Gmail / WhatsApp etc). I am able to do this using FileProvider, and it works OK for WhatsApp. When choosing to share on Gmail the photo is correctly attached, but the Uri that I pass via Intent.EXTRA_STREAM also ends up being parsed by Gmail as an address in the "To:" field of the newly composed email, along with the address(es) that I pass via Intent.EXTRA_EMAIL.

So the user is required to delete the bogus (Uri) email address before sending. Any idea how to prevent this from happening?

Uri contentUri = FileProvider.getUriForFile(getActivity(), "com.mypackage.fileprovider", cacheFile);

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setDataAndType(contentUri, "image/jpeg");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {"some_address@gmail.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Photo");
intent.putExtra(Intent.EXTRA_TEXT, "Check out this photo");
intent.putExtra(Intent.EXTRA_STREAM, contentUri);

if(intent.resolveActivity(getActivity().getPackageManager()) != null)
{
    startActivity(Intent.createChooser(intent, getString(R.string.share_file)));
}
Simon Huckett
  • 482
  • 5
  • 13

1 Answers1

17

Replace:

intent.setDataAndType(contentUri, "image/jpeg");

with:

intent.setType("image/jpeg");

Your problem is not EXTRA_STREAM, but rather that you are putting the Uri in the Intent's data facet.

Also, if your minSdkVersion is below 21, you will need to take some extra steps to ensure that clients can read the content, as the Intent flag is not applied to EXTRA_STREAM automatically on earlier versions of Android.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 2
    Thanks, that's fixed it. Huge respect for the speed of your answer. Have spent a couple of hours searching around for a solution to no avail. Would vote you up if only I could.... – Simon Huckett Oct 06 '16 at 14:42
  • 1
    You just got to love SO. Android behaves so strange sometimes - we'd all be damned without this platform and people like you. – Oliver Metz Dec 18 '18 at 21:41