Opening an email with multiple attachments, while restricting the chooser to ONLY email apps?

喜欢而已 提交于 2019-12-24 05:49:30

问题


What is the best way on Android to send an email with multiple attachments without having non-email apps in the chooser?

When sending emails, I used to do it like this:

final Intent sendEmailIntent = new Intent(Intent.ACTION_SEND);
sendEmailIntent.setType("message/rfc822");
sendEmailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "test@test.com" });
...

Unfortunately, "message/rfc822" no longer works well for filtering out undesired apps from the chooser, such as Evernote, Drive, and various other apps.

I recently found this workaround that works for single attachments:

sendEmailIntent = new Intent(Intent.ACTION_SENDTO);
Uri data = Uri.parse("mailto:?to=test@test.com&subject...");
sendEmailIntent.setData(data);  
...

Unfortunately, this doesn't work for multiple attachments. I tried it, and it crashes Gmail. :S


回答1:


I finally found a solution, albeit one that only works on Ice Cream Sandwich MR1 and above. The trick is to first build your intent using ACTION_SEND_MULTIPLE:

sendEmailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
sendEmailIntent.setType("message/rfc822");
sendEmailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "some@email.com" });                
sendEmailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
sendEmailIntent.putExtra(Intent.EXTRA_TEXT, "Body");
final ArrayList<Uri> uris = /* ... Your code to build the attachments. */
sendEmailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);

To restrict it to email apps only, add this code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
    sendEmailIntent.setType(null); // If we're using a selector, then clear the type to null. I don't know why this is needed, but it doesn't work without it.
    final Intent restrictIntent = new Intent(Intent.ACTION_SENDTO);
    Uri data = Uri.parse("mailto:?to=some@email.com");
    restrictIntent.setData(data);
    sendEmailIntent.setSelector(restrictIntent);
}

When you fire this intent with startActivity(), you'll now only see email apps in the list, and if you select Gmail, the multiple attachments will be there.

I do this with a try/catch in case startActivity resolves to no activities, in which case I remove the selector, and it seems to work well.



来源:https://stackoverflow.com/questions/22240028/opening-an-email-with-multiple-attachments-while-restricting-the-chooser-to-onl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!