Android項目實戰(六十八):微信分享的實現

系統分享:

// 系統轉發方式
    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://"開頭的用於共享的路徑
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章