按包名称为共享意图创建自定义选择器

时间:2015-03-08 20:52:18

标签: android android-intent android-package-managers

我的Android活动中有一个Text,我想让用户选择在whatsapp,line,facebook,twitter等社交应用上分享。

但我想创建一个自定义选择器,以便它不会在选择器中显示非预期的应用程序。

我知道这个片段

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
startActivity(Intent.createChooser(shareIntent, "Share via"));

如何制作它以便在选择器中它只显示我可以通过其包名指定的应用程序。

由于

1 个答案:

答案 0 :(得分:0)

即使我认为这个问题是重复的,但由于我找不到重复的问题,请先提供答案。

List<Intent> targetedShareIntents = new ArrayList<Intent>();
Intent shareInent = new Intent(Intent.ACTION_SEND);
shareInent.setType("text/plain");
List<ResolveInfo> resInfo = activity.getPackageManager().queryIntentActivities(shareInent, 0);
// put the name of the packages you want in this ArrayList
ArrayList<String> wantedPackage = new ArrayList<>();

if (!resInfo.isEmpty()) {
    for (ResolveInfo info : resInfo) {
        Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
        targetedShare.setType("text/plain");
        String infoPackageName = info.activityInfo.packageName.toLowerCase();

        if (wantedPackage.contains(infoPackageName)) {
            targetedShare.putExtra(Intent.EXTRA_TEXT, "put your text here");
            targetedShare.setPackage(info.activityInfo.packageName.toLowerCase());
            targetedShareIntents.add(targetedShare);
            resPackageNames.add(infoPackageName);
        }
    }
    Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Chooser title");
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
    startActivity(chooserIntent);
}