How do I create an intent to launch any e-mail app

2019-04-12 13:42发布

问题:

I have found various topics here and elsewhere on creating an intent for sending e-mail and that seems to be pretty straightforward. I'm looking for an intent to just launch any e-mail client the user might have.

Here is the code I've seen for sending an e-mail (posted just for reference, this doesn't serve my needs as I don't want to send a new message):

Intent i = new Intent(Intent.ACTION_SEND); 
i.setType("text/plain"); 
i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"recipient@example.com"}); 
i.putExtra(Intent.EXTRA_SUBJECT, "Subject of the message"); 
i.putExtra(Intent.EXTRA_TEXT   , "Body of the message"); 

Here is the code I put together for specifically launching the Gmail client by package name:

PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("com.google.android.gm");
startActivity(intent);

The code above works but isn't flexible in that a user might not be using Gmail but the other built-in e-mail application or a 3rd party e-mail app. I'm looking for an intent that would bring up the chooser in this case so the user can decide which app to launch to read e-mail.

Does anyone know how to accomplish this?

回答1:

Does anyone know how to accomplish this?

There is no such Intent -- you can tell this by examining the manifest for the Email application.

The only thing you can do is build yourself a list of email clients you wish to link to and use the PackageManager code you show above for each.



回答2:

Can a mailto URL be used in some fashion to accomplish this? --Edit-- I was able to accomplish this using the following code sample:

mt = MailTo.parse("mailto:yourname@gmail.com");
sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{mt.getTo()});
sendIntent.putExtra(Intent.EXTRA_TEXT, "");
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Enter a subject");
sendIntent.setType("message/rfc822");
startActivity(Intent.createChooser(sendIntent, "Send a Message:"));


回答3:

Another approach could be Intent.createChooser(); and let the user to choose the right application.

BTW The list could contain not only email applications