Creating custom chooser for share intent by package name

社会主义新天地 提交于 2019-12-24 15:41:55

问题


I have a Text in my android activity and I want give the user option to share it on social apps like whatsapp, line, facebook, twitter etc.

But I want to create a custom chooser so that it won't show unintended apps in the chooser.

I'm aware of this snippet

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

How can I make it so that in the chooser it'd only show the apps which I can specify by their package names.

Thanks


回答1:


Even though I think this question is duplicated, but since I can't find the duplicated question yet, let me provide an answer first.

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);
}


来源:https://stackoverflow.com/questions/28931744/creating-custom-chooser-for-share-intent-by-package-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!