Android 使用微信登錄、分享功能 具體的文檔詳情微信官網上介紹(微信官網文檔),本人直接按照項目部署步驟進行講解: 第一步:申請你的AppID; 第二步:依賴 或者: 這兩個依賴包的區別是前者包含統計功能,後者沒有。 第三步:在AndroidManifest.xml中加入必須的許可權 第四步:註 ...
Android 使用微信登錄、分享功能
具體的文檔詳情微信官網上介紹(微信官網文檔),本人直接按照項目部署步驟進行講解:
第一步:申請你的AppID;
第二步:依賴
dependencies { compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:1.0.2' }
或者:
dependencies { compile 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:1.0.2' }
這兩個依賴包的區別是前者包含統計功能,後者沒有。
第三步:在AndroidManifest.xml中加入必須的許可權
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.READ_PHONE_STATE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
第四步:註冊到微信,微信的SDK在使用之前需要調用代碼進行註冊,註冊可以是在調用微信SDK的Activity,但最好還是放到入口Activity或者Application中;
WxApplication.java
public static String APP_ID="你的APPID"; public static IWXAPI api; public void onCreate() { super.onCreate(); api = WXAPIFactory.createWXAPI(this, APP_ID, true); api.registerApp(APP_ID); }
第五步:微信登錄。
5.1 點擊你的微信登錄按鈕,進行微信授權,首先需要獲取一個code值,在包名下新建一個包,這裡必須這樣,不能隨意命名,比如你的項目包名是:come.shenhua.wx則新建的包為come.shenhua.wx.wxapi在該包下創建一個WXEntryActivity繼承IWXAPIEventHandler;(註意Activity的命名也不能隨意更改)
LoginActivity.java
private void onClickWeChatLogin() { if (WxApplicaiton.api == null) { WxApplication.api = WXAPIFactory.createWXAPI(this, WxApplication.APP_ID, true); } if (!WxApplication.api.isWXAppInstalled()) { ToastUtils.toast("您手機尚未安裝微信,請安裝後再登錄"); return; } WxApplication.api.registerApp(WxApplication.APP_ID); SendAuth.Req req = new SendAuth.Req(); req.scope = "snsapi_userinfo"; req.state = "wechat_sdk_xb_live_state";//官方說明:用於保持請求和回調的狀態,授權請求後原樣帶回給第三方。該參數可用於防止csrf攻擊(跨站請求偽造攻擊),建議第三方帶上該參數,可設置為簡單的隨機數加session進行校驗 WxApplication.api.sendReq(req); }
在AndroidManifest.xml中加入,(android:exported="true" 一定不能少)
<activity android:name=".wxapi.WXEntryActivity" android:exported="true" />
WXEntryActivity.java
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler { public static final String TAG = WXEntryActivity.class.getSimpleName(); public static String code; public static BaseResp resp = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_wxentry); boolean handleIntent = XBLiveApplication.api.handleIntent(getIntent(), this);
//下麵代碼是判斷微信分享後返回WXEnteryActivity的,如果handleIntent==false,說明沒有調用IWXAPIEventHandler,則需要在這裡銷毀這個透明的Activity; if(handleIntent==false){ Log.d(TAG, "onCreate: "+handleIntent); finish(); } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); XBLiveApplication.api.handleIntent(intent, this); } @Override public void onReq(BaseReq baseReq) { Log.d(TAG, "onReq: "); finish(); } @Override public void onResp(BaseResp baseResp) { if (baseResp != null) { resp = baseResp; code = ((SendAuth.Resp) baseResp).code; //即為所需的code } switch (baseResp.errCode) { case BaseResp.ErrCode.ERR_OK: Log.d(TAG, "onResp: 成功"); finish(); break; case BaseResp.ErrCode.ERR_USER_CANCEL: Log.d(TAG, "onResp: 用戶取消"); finish(); break; case BaseResp.ErrCode.ERR_AUTH_DENIED: Log.d(TAG, "onResp: 發送請求被拒絕"); finish(); break; } }
resp和code定義成全局變數,在WXEntryWActivity頁面銷毀後登錄頁面會走onResume()方法,在這裡開始其他操作
5.2 拿到code後在登錄頁面通過code獲取access_token,官網的說法是:“access_token是調用授權關係介面的調用憑證,由於access_token有效期(目前為2個小時)較短,當access_token超時後,可以使用refresh_token進行刷新”,所以拿到access_token後再次請求進行refresh_token,刷新後拿到access_token即可發送請求獲取微信用戶信息了;
獲取access_token的URL:AccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=你的appid&secret=你的AppSecret&code=授權獲取到的code&grant_type=authorization_code";
刷新access_token的URL:Refresh_tokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=你的appid&grant_type=refresh_token&refresh_token=上一步請求到的access_token;
獲取用戶信息URL:UserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=刷新的access_token&openid=刷新access_token時獲取的openid;
@Override protected void onResume() { Log.d(TAG, "onResume: 1"); super.onResume(); //這裡的判斷是為了區分如果不是不是從WXEntryActivity頁面銷毀重啟的,不走下麵的代碼 if (WXEntryActivity.resp != null) { if (WXEntryActivity.resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) { Thread thread = new Thread(downloadRun); thread.start(); try { thread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public Runnable downloadRun = new Runnable() { @Override public void run() { WXGetAccessToken(); } }; //根據code獲取access_token,這裡用第三方volley框架進行post請求 private void WXGetAccessToken() { String getAccessTokenUrl = AccessTokenUrl; StringRequest request = new StringRequest(Request.Method.GET, getAccessTokenUrl, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "onResponse: " + response); Gson gson = new Gson(); WeChatLoginTokenModel tokenModel = gson.fromJson(response, WeChatLoginTokenModel.class); refresh_token = tokenModel.getRefresh_token(); WXGetRefreshAccessToken(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); request.setTag("weChatGetToken"); XBLiveApplication.getHttpRequestQueue().add(request); } //拿到access_token後再次發送請求進行刷新access_token,拿到access_refresh和openid private void WXGetRefreshAccessToken() { String getRefresh_tokenUrl =Refresh_tokenUrl ; StringRequest request = new StringRequest(Request.Method.GET, getRefresh_tokenUrl, new Response.Listener<String>() { @Override public void onResponse(String response) { Gson gson = new Gson(); WeChatLoginTokenModel tokenModel = gson.fromJson(response, WeChatLoginTokenModel.class); String access_token = tokenModel.getAccess_token(); String openid = tokenModel.getOpenid(); WXGetUserInfo(access_token, openid); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); request.setTag("weChatGetRefreshToken"); XBLiveApplication.getHttpRequestQueue().add(request); } //獲取用戶信息 private void WXGetUserInfo(String access_token, String openid) { String getUserInfoUrl =UserInfoUr; StringRequest request = new StringRequest(Request.Method.GET, getUserInfoUrl, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "onResponse3: " + response); Gson gson = new Gson(); WeChatUserInfoModel userInfoModel = gson.fromJson(response, WeChatUserInfoModel.class); String city = userInfoModel.getCity(); String userName = userInfoModel.getNickname(); String userIcon = userInfoModel.getHeadimgurl(); int sex = userInfoModel.getSex();//1:男;0:女;2:未知 String province = userInfoModel.getProvince(); openId_WX = userInfoModel.getOpenid(); ToastUtils.toast("登錄成功"); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } });
//下麵代碼是volley框架註冊,請忽視 request.setTag("weChatGetUserInfo"); XBLiveApplication.getHttpRequestQueue().add(request); }
註意一點:在做測試時,微信的應用簽名必須要保持一致,比如你在官網填寫的是沒有打包簽名的應用簽名,你測試的APP也沒有打包簽名,那麼是沒有問題,但是如果你微信官網上填寫的是已經上線經過打包簽名的應用簽名,那你在做測試時必須要用打包簽名的應用去做測試。
第六步:微信分享到朋友圈、微信好友、添加微信收藏:
分享收藏基本完全一樣,也是需要先進行註冊的,如果之前已經進行了註冊就不需要註冊,否則在調用分享的Activity中或者全局Application中進行註冊;scene 有一下三種:
SendMessageToWX.Req.WXSceneSession;分享到微信好友
SendMessageToWX.Req.WXSceneTimeline;分享到微信朋友圈
SendMessageToWX.Req.WXSceneFavorite;添加到微信收藏夾
分享純文本內容:
// 初始化一個WXTextObject對象 WXTextObject textObj = new WXTextObject(); textObj.text = text; // 用WXTextObject對象初始化一個WXMediaMessage對象 WXMediaMessage msg = new WXMediaMessage(); msg.mediaObject = textObj; // 發送文本類型的消息時,title欄位不起作用 // msg.title = "Will be ignored"; msg.description = text; // 構造一個Req SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("text"); // transaction欄位用於唯一標識一個請求 req.message = msg; req.scene = isTimelineCb.isChecked() ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession; // 調用api介面發送數據到微信 api.sendReq(req);
分享音樂:
WXMusicObject music = new WXMusicObject(); music.musicUrl="http://staff2.ustc.edu.cn/~wdw/softdown/index.asp/0042515_05.ANDY.mp3"; WXMediaMessage msg = new WXMediaMessage(); msg.mediaObject = music; msg.title = "Music Title "; msg.description = "Music Album "; Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.send_music_thumb); msg.thumbData = Util.bmpToByteArray(thumb, true); SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("music"); req.message = msg; req.scene = isTimelineCb.isChecked() ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession; api.sendReq(req);
分享網頁:
WXWebpageObject webpage = new WXWebpageObject(); webpage.webpageUrl = "http://www.qq.com"; WXMediaMessage msg = new WXMediaMessage(webpage); msg.title = "WebPage Title "; msg.description = "WebPage Description "; Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.send_music_thumb); Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true); bmp.recycle(); msg.thumbData = Util.bmpToByteArray(thumbBmp, true); SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("webpage"); req.message = msg; req.scene = mTargetScene; api.sendReq(req);
具體可參照官網Demo。(可分享純文本內容,照片,音樂,視頻,網頁,鏈接等等)
樓主在測試時發現,如果我分享的網頁要顯示一張圖片,官方Demo給的是一張本地照片,而我的是圖片地址,我做了一下處理:
點擊分享時先載入圖片,寫了一個while迴圈,直到拿到bitmap為止;
case R.id.line_share_wechat: if (!api.isWXAppInstalled()) { ToastUtils.toast("您手機尚未安裝微信,請安裝後再登錄"); return; } if (api == null) { api = WXAPIFactory.createWXAPI(this,APP_ID, true); } mTargetScene = SendMessageToWX.Req.WXSceneSession;//share to wx gotoDownLoadSharePic();break;
private void gotoDownLoadSharePic() { new Thread() { @Override public void run() { URL url = null; try { url = new URL(thumb); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.connect(); InputStream inputStream = conn.getInputStream(); bmp = BitmapFactory.decodeStream(inputStream); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }.start(); while (bmp == null) { Log.d(TAG, "onClick: bmp=" + bmp); } goToShareToWeChat(mTargetScene); } private void goToShareToWeChat(int targetScene) { WXWebpageObject mWebPage = new WXWebpageObject(); mWebPage.webpageUrl = Constants.SHARE_QQ_URL + vid; msg = new WXMediaMessage(mWebPage); if (targetScene == SendMessageToWX.Req.WXSceneTimeline || targetScene == SendMessageToWX.Req.WXSceneFavorite) { msg.title = mTitleContent; } else { msg.title = name; msg.description = mTitleContent; } msg.setThumbImage(bmp); SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("webpage"); req.message = msg; req.scene = targetScene; api.sendReq(req); }