前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android项目实战(六十八):微信分享的实现

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

作者头像
听着music睡
发布2024-01-06 10:57:29
1160
发布2024-01-06 10:57:29
举报
文章被收录于专栏:Android干货Android干货

系统分享:

代码语言:javascript
复制
// 系统转发方式
    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分享:

代码语言:javascript
复制
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://"开头的用于共享的路径
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-01-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档