Android 通过Intent简单实现分享功能

现在大多数App的分享功能基本上使用的都是微信、QQ、微博的分享sdk或者是集成友盟分享sdk,如果想简单快速的实现分享功能,可以考虑通过Intent方式打开在系统中安装的具有分享功能的App的分享页面。方法如下:

public static List<ResolveInfo> shareIntentActivities(Context context){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intnet.setType("text/plain");
    PackageManager packageManager = context.getPackageManager();
    List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, 0);
    return resloveInfos;
}

如果只需要QQ和微信分享,可以进行如下操作:

public static List<ResolveInfo> shareIntentActivities(Context context){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intnet.setType("text/plain");
    PackageManager packageManager = context.getPackageManager();
    List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, 0);
    List<ResolveInfo> shareItems = new ArrayList();    
    for(ResolveInfo info: resolveInfos) {
        String name = info.activityInfo.packageName;
        if (TextUtils.equals(packageName, "com.tencent.mm")
                    || TextUtils.equals(packageName, "com.tencent.mobileqq")) {
                shareItems.add(resolveInfo);
        }
    }
    return shareItems;
}

通过ResolveInfo获取图标ICONLabel:

Drawable drawable = resloveInfo.loadIcon(packageManager);
CharSequence label = resolveInfo.loadLabel(packageManager);

通过Intent发起分享:

public static void share(Context context, 
            ResolveInfo info, String shareContent){
    Intent itnent = new Intent();
    intnet.setAction(Intent.ACTION_SEND);
    String pkg = resolveInfo.activityInfo.packageName;
    String cls = resolveInfo.activityInfo.name;
    intent.setComponent(new Component(pkg, cls));
    intent.putExtra(Intent.EXTRA_TEXT, shareContent);
    context.startActivity(intent);
}

原文地址:https://xiaowujiang.cn/posts/73a6d0c4/
更多内容:https://www.xiaowujiang.cn

posted @ 2020-04-29 17:56  jxiaow  阅读(125)  评论(0编辑  收藏