我通过使用 EXTRA_INITIAL_INTENTS 找到了部分解决方案:
Intent viewIntent = new Intent(Intent.ACTION_VIEW);
Intent editIntent = new Intent(Intent.ACTION_EDIT);
viewIntent.setDataAndType(uri, type);
editIntent.setDataAndType(uri, type);
Intent chooserIntent = Intent.createChooser(editIntent, "Open in...");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { viewIntent });
startActivity(chooserIntent);
我说部分是因为如果一个应用程序同时支持 ACTION_VIEW 和 ACTION_EDIT ,它将在列表中显示两次,其中一个将打开文件进行查看,另一个用于编辑,并且您不一定知道哪个是哪个。我认为完整的解决方案需要一个自定义应用程序选择器,正如蒂姆建议的那样。
编辑(完整的解决方案!):
我找到了一个不涉及编写自定义应用程序选择器的解决方案。为了区分 ACTION_EDIT 应用程序和 ACTION_VIEW 应用程序,我找到了一种方法,通过使用 Tim 提供的代码行,将“(用于编辑)”字符串附加到其中一个应用程序的标签(在我的例子中为 ACTION_EDIT)。此外,为了确保附加字符串不会出现为应用程序名称的一部分,我将其颜色更改为青色:
PackageManager pm = kyoPrint.getPackageManager();
Intent viewIntent = new Intent(Intent.ACTION_VIEW);
Intent editIntent = new Intent(Intent.ACTION_EDIT);
viewIntent.setDataAndType(uri, type);
editIntent.setDataAndType(uri, type);
Intent openInChooser = Intent.createChooser(viewIntent, "Open in...");
// Append " (for editing)" to applicable apps, otherwise they will show up twice identically
Spannable forEditing = new SpannableString(" (for editing)");
forEditing.setSpan(new ForegroundColorSpan(Color.CYAN), 0, forEditing.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
List<ResolveInfo> resInfo = pm.queryIntentActivities(editIntent, 0);
Intent[] extraIntents = new Intent[resInfo.size()];
for (int i = 0; i < resInfo.size(); i++) {
// Extract the label, append it, and repackage it in a LabeledIntent
ResolveInfo ri = resInfo.get(i);
String packageName = ri.activityInfo.packageName;
Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
intent.setAction(Intent.ACTION_EDIT);
intent.setDataAndType(uri, type);
CharSequence label = TextUtils.concat(ri.loadLabel(pm), forEditing);
extraIntents[i] = new LabeledIntent(intent, packageName, label, ri.icon);
}
openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
startActivity(openInChooser);
编辑2:错误
如果第一个意图没有找到任何活动,则不会显示任何活动,包括第二个意图找到的任何活动。我最终编写了自己的选择器。我只是填充了 ExpandableListView,其中包含每种意图类型的标题及其各自作为子项的活动(存储为单独的 LabeledIntents)。