如何在 createchooser 上自动选择电子邮件应用程序?

Jap*_*apz 3 android android-intent

如何自动获取/选择处理指定意图的第一个应用程序,就像用户选择了createChooser()对话框中的第一个选项一样。

在此示例中,在发送电子邮件等数据的应用程序之间进行选择:

final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); SendEmailActivity.this.startActivity(Intent.createChooser(1, "Send mail..."));

请帮忙。

Str*_*ero 5

使用此问题答案,您可以获得所有意图的应用程序列表android.content.Intent.ACTION_SEND

这是我在下面编写的一个工作示例(最终在我的设备上选择了 gmail)

**公平警告 - 如果没有设置电子邮件帐户,将抛出 NullPointerException 您应该在变量上添加空检查pkgAppsList并告诉用户没有找到或已设置电子邮件应用程序

    //set the main intent to ACTION_SEND for looking for applications that share information
    Intent intent = new Intent(Intent.ACTION_SEND, null);

    //intent.addCategory(Intent.CATEGORY_LAUNCHER); //if you want extra filters

    //filter out apps that are able to send plain text
    intent.setType("plain/text");

    //get a list of apps that meet your criteria above
    List<ResolveInfo> pkgAppsList = this.getPackageManager().queryIntentActivities( intent, PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_RESOLVED_FILTER);

    //select the first one in the list
    ResolveInfo info = pkgAppsList.get(0);      
    String packageName = info.activityInfo.packageName;
    String className = info.activityInfo.name;

    //set the intent to luanch that specific app
    intent.setClassName(packageName, className);

    //some samples on adding more then one email address
    String aEmailList[] = { "user@fakehost.com","user2@fakehost.com" };
    String aEmailCCList[] = { "user3@fakehost.com","user4@fakehost.com"};
    String aEmailBCCList[] = { "user5@fakehost.com" };

    //all the extras that will be passed to the email app       
    intent.putExtra(android.content.Intent.EXTRA_EMAIL, aEmailList);
    intent.putExtra(android.content.Intent.EXTRA_CC, aEmailCCList);
    intent.putExtra(android.content.Intent.EXTRA_BCC, aEmailBCCList);
    intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My subject");
    intent.putExtra(android.content.Intent.EXTRA_TEXT, "My message body.");

    //start the app
    startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

如果您想将正在调用的应用程序列入白名单,您可以遍历列表检查特定软件包的每个软件包名称(例如:gmail 是“com.google.android.gm”)