Android平台分享之微信

微信分享申请过程比较麻烦,在这里就不去介绍了。可以上官网去查看教程。

  1. 清单文件配置


  1. 初始化
private IWXAPI mAPI;
//注册微信
mAPI = WXAPIFactory.createWXAPI(this, BaseConstants.WX_APP_KEY);
mAPI.registerApp(BaseConstants.WX_APP_KEY);
  1. 分享方法,包括分享到好友和朋友圈
public void shareToWX(IWXAPI mAPI, String text, Bitmap bitmap, boolean friend) {
    Log.i(TAG, "share to wx");
    WXImageObject mWXImage = new WXImageObject(bitmap);
    WXMediaMessage mWXMsg = new WXMediaMessage();
    mWXMsg.mediaObject = mWXImage; //图片
    mWXMsg.title = text; //文本描述
    /*Bitmap thumb = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
    mWXMsg.thumbData = ImageUtil.bmpToByteArray(thumb, true); //设置缩略图*/
    //构造一个Req
    SendMessageToWX.Req mReq = new SendMessageToWX.Req();
    if (friend) {
        mReq.scene = SendMessageToWX.Req.WXSceneSession; //分享至好友
    } else {
        int sdkApi = mAPI.getWXAppSupportAPI();
        if (sdkApi >= 0x21020001) {
            mReq.scene = SendMessageToWX.Req.WXSceneTimeline; //分享至朋友圈
        } else {
            Toast.makeText(mContext, mContext.getString(R.string.WX_DO_NOT_SUPPORT_SHARE_TO_MOMEN),
                    Toast.LENGTH_SHORT).show();
            return;
        }
    }
    mReq.transaction = String.valueOf(System.currentTimeMillis());
    mReq.message = mWXMsg;
    mAPI.sendReq(mReq); //分享调用
}
  1. 重写回调类
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private final String TAG = WXEntryActivity.class.getSimpleName();
    private IWXAPI mWXAPI;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mWXAPI = WXAPIFactory.createWXAPI(this, BaseConstants.WX_APP_KEY, false);
        mWXAPI.handleIntent(getIntent(), this);
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mWXAPI.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }
    //第三方应用发送请求到微信的请求处理后的响应结果
    @Override
    public void onResp(BaseResp baseResp) {
        switch ( baseResp.errCode  ){
            case BaseResp.ErrCode.ERR_OK:
                Toast.makeText(this, getString(R.string.WEIBO_SHARE_SUCCESS), Toast.LENGTH_SHORT).show();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Toast.makeText(this, getString(R.string.WEIBO_SHARE_CANCELED), Toast.LENGTH_SHORT).show();
                break;
            case BaseResp.ErrCode.ERR_SENT_FAILED:
                Toast.makeText(this, getString(R.string.WEIBO_SHARE_FAILED), Toast.LENGTH_SHORT).show();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Log.i(TAG, "授权失败");
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                break;
        }
        finish();
    }
}

你可能感兴趣的:(Android平台分享之微信)