Android项目实战(六十八):微信分享的实现

发布时间 2024-01-05 14:27:51作者: 听着music睡

系统分享:

// 系统转发方式
    public static void shareBySystem(Context context,File file){
        WxUtils.checkFileUriExposure();
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID.concat(".fileprovider"), file);
        intent.putExtra(Intent.EXTRA_STREAM,
                contentUri);  //传输图片或者文件 采用流的方式
        intent.setType("*/*");   //分享文件
        if (Build.VERSION.SDK_INT >= 24) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        ArmsUti

 

微信api分享:

public static void sendFile(Context context , String url , String title , String memo , int mTargetScene){
        IWXAPI api = WXAPIFactory.createWXAPI(context, XApplication.APP_ID,false);
        WXFileObject fileObject = new WXFileObject();
        // 兼容fileprovider,获取文件url
        fileObject.filePath = getFileUri(context,new File(url));

        //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
        WXMediaMessage msg = new WXMediaMessage(fileObject);
        msg.title = title ;
        msg.description = memo;
        Bitmap thumbBmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_share);
        msg.thumbData = bmpToByteArray(thumbBmp, true);

        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("file");
        req.message =msg;
        req.scene =mTargetScene;
        //调用api接口,发送数据到微信
        api.sendReq(req);
    }

    // https://developers.weixin.qq.com/community/develop/doc/0004886026c1a8402d2a040ee5b401
    // OpenSDK支持FileProvider方式分享文件到微信官方
    public static String getFileUri(Context context, File file) {
        if (file == null || !file.exists()) {
            return null;
        }
        Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID.concat(".fileprovider"), file);
        // 授权给微信访问路径
        context.grantUriPermission("com.tencent.mm",  // 这里填微信包名
                contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        return contentUri.toString();   // contentUri.toString() 即是以"content://"开头的用于共享的路径
    }