實現將網頁連結分享到微信功能
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 = “
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版本