通过程序包名称为共享意图创建自定义选择器 [英] Creating custom chooser for share intent by package name

查看:47
本文介绍了通过程序包名称为共享意图创建自定义选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的android活动中有一个Text,我想给用户选项以在社交应用(例如whatsapp,line,facebook,twitter等)上共享该文本.

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.

我知道此代码段

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.

谢谢

推荐答案

即使我认为这个问题是重复的,但是由于我仍然找不到重复的问题,所以让我先提供一个答案.

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

这篇关于通过程序包名称为共享意图创建自定义选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆