1、在app的build.gradle文件中添加依赖
compile ‘com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+’
2、在需要的控件(Dialog、Activity)里初始化APP_ID,在对应的onCreate()方法里注册到微信
//微信
private static final String APP_ID = “你申请的app_id”;
private IWXAPI mWXapi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//注册微信
mWXapi = WXAPIFactory.createWXAPI(context, APP_ID, true);
mWXapi.registerApp(APP_ID);
}
3、点击时,分享
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.rl_item_invite:
Log.d(“TAG”, “邀请wx:跳转微信”);
sendWXweb(0);
this.dismiss();
break;
case R.id.tv_dialog_invite_cancel:
this.dismiss();
break;
}
}
private void sendWXweb(int scene) {
WXWebpageObject web = new WXWebpageObject();
web.webpageUrl = “http://www.baidu.com/“;
WXMediaMessage msg = new WXMediaMessage(web);
msg.title = "标题";
msg.description = "内容描述";
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon_logo);
msg.setThumbImage(bitmap);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = String.valueOf(System.currentTimeMillis());
req.message = msg;
req.scene = scene == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
mWXapi.sendReq(req);
}
4、如果需要微信返回结果,在包名下建个wxapi文件夹,在里面新建一个WXEntryActivity
public class WXEntryActivity extends Activity implements IWXAPIEventHandler{
// IWXAPI 是第三方app和微信通信的openapi接口
private IWXAPI api;
@Override
protected void onCreate(Bundle savedInstanceState) {
api = WXAPIFactory.createWXAPI(this, “你的APP_ID”, false);
api.handleIntent(getIntent(), this);
super.onCreate(savedInstanceState);
}
@Override
public void onReq(BaseReq baseReq) {
}
@Override
public void onResp(BaseResp baseResp) {
switch (baseResp.errCode) {
case BaseResp.ErrCode.ERR_OK:
//分享成功
ToastUtils.showToast("分享成功");
this.finish();
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
//分享取消
ToastUtils.showToast("分享取消");
this.finish();
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
//分享拒绝
ToastUtils.showToast("分享拒绝");
this.finish();
break;
}
}
}
OK,过程就是这样!但最后一定要注意:
1、分享到微信一定要签名打包后才能测试!
2、一定要检查安装在测试机上apk用签名工具生成的签名文件,和微信开放平台的签名文件一致!!!
不一致的话:
1、检查源码的包名,是否正确;
2、检查安装的是不是签过名的:是app-release.apk,不能是app-dubeg.apk版本