如何使用包管理器为应用程序列表创建选择器

How to create a chooser for a list of applications using package manager

基本上我有一个流行的电子邮件应用程序包名称列表,我想创建一个选择器来启动发送电子邮件意图,你可以参考this 问题,在这里他只使用 gmail 的包管理器,我想为包列表这样做

What I want to do is simulate the desktop behavior when you click on an email link which opens outlook/gmail client with the to field set to the email id, but in addition to this I want to let the user choose the email application that is launched

startActivity(new Intent(Intent.ACTION_SENDTO)
  .setData(Uri.parse("mailto:"+yourEmailAddressGoesHere)));

yourEmailAddressGoesHere 替换为 "the email id"。

如果用户有多个电子邮件客户端,并且用户没有选择默认电子邮件客户端,用户将自动获得一个选择器。如果用户只有一个电子邮件客户端,或者选择了默认的电子邮件客户端,这将引导用户activity向您指定的电子邮件地址撰写邮件。

创建意图添加设置其 uri 数据

Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);

然后创建选择器意图。当您希望用户每次发送电子邮件时都选择他想要的应用程序时,这很有用。如果你想选择一个应用程序并将其设为默认,你可以省略选择器并直接启动意图

Intent chooser = Intent.createChooser(intent, "Chooser title");

然后检查是否至少有一个 activity 可以处理电子邮件意图

if(intent.resolveActivity(getPackageManager()) != null){
    // there are apps, start the chooser
    startActivity(chooser);
} else {
    // no apps found
    Toast.makeText(this, "No apps found", Toast.LENGTH_SHORT).show();
}