美文网首页
QQ、微信直接分享工具类 - Android

QQ、微信直接分享工具类 - Android

作者: LeveyChen | 来源:发表于2018-08-29 14:04 被阅读0次

只是做简单分享,又不想集成那些乱七八糟的分享组件。
那么。。以下是一个QQ、微信直接分享工具类。
可以直接分享图片。

public class ShareUtils {

    public static int QQ = 1;
    public static int WX = 2;

    public ShareUtils(Context context,String path,int type) {
        if(type==QQ){
            shareImage(context,path,new ShareItem("QQ","com.tencent.mobileqq.activity.JumpActivity","com.tencent.mobileqq"));
        }
        if(type==WX){
            shareImage(context,path,new ShareItem("微信","com.tencent.mm.ui.tools.ShareImgUI", "com.tencent.mm"));
        }
    }

    private void shareImage(Context context, String imageUrl,ShareItem share) {
        if (!share.packageName.isEmpty() && !isAvailable(context, share.packageName)) {
            Sys.toast(context,"请先安装 " + share.title);
            return;
        }
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path)));
        if(!share.packageName.isEmpty()) {
            shareIntent.setComponent(new ComponentName(share.packageName,share.activityName));
            context.startActivity(shareIntent);
        }
        else {
            context.startActivity(Intent.createChooser(shareIntent,Intent.ACTION_ALL_APPS));
        }

    }

    public boolean isAvailable(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> info = packageManager.getInstalledPackages(0);
        for (int i = 0; i < info.size(); i++) {
            if (info.get(i).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }

    private class ShareItem {
        String title,activityName,packageName;
        public ShareItem(String title,String activityName, String packageName) {
            this.title = title;
            this.activityName = activityName;
            this.packageName = packageName;
        }
    }

相关文章

网友评论

      本文标题:QQ、微信直接分享工具类 - Android

      本文链接:https://www.haomeiwen.com/subject/hlohwftx.html