Android WeChat logon and sharing, android sharing

Source: Internet
Author: User
Tags openid

Android logon and sharing, android sharing

Android login and sharing functions

For details about the specific document, visit the official website (Official Website). I will explain it directly according to the project deployment steps:

Step 1: Apply for your AppID;

Step 2: dependency

dependencies {    compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:1.0.2'}

Or:

dependencies {    compile 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:1.0.2'}

The difference between the two dependent packages is that the former includes the statistical function, while the latter does not.

Step 3: Add required permissions to 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"/>

Step 4: register the SDK. before using the SDK, you must call the code to register the SDK. You can call the SDK Activity, but you 'd better put it in the portal Activity or Application;

WxApplication. java

Public static String APP_ID = "Your APPID"; public static IWXAPI api; public void onCreate () {super. onCreate (); api = wxapifacloud. createWXAPI (this, APP_ID, true); api. registerApp (APP_ID );}

Step 5: log on.

5.1 click your login button to grant permissions. First, you need to obtainCodeValue, create a new package under the package name. This is required and cannot be named at will. For example, your project package name is: come. shenhua. wx indicates that the new package is come. shenhua. wx. wxapi creates a WXEntryActivity under this package to inherit IWXAPIEventHandler. (Note that the name of the Activity cannot be changed at will)

LoginActivity. java

  

Private void onClickWeChatLogin () {if (WxApplicaiton. api = null) {WxApplication. api = wxapifacloud. createWXAPI (this, WxApplication. APP_ID, true);} if (! WxApplication. api. isWXAppInstalled () {ToastUtils. toast ("your mobile phone has not been installed, please install it before login"); return;} WxApplication. api. registerApp (WxApplication. APP_ID); SendAuth. req req = new SendAuth. req (); req. scope = "snsapi_userinfo"; req. state = "wechat_sdk_xb_live_state"; // official description: used to maintain the request and callback status. The authorization request is returned to a third party as it is. This parameter can be used to prevent csrf attacks (cross-site request forgery attacks). We recommend that you add this parameter to a third party and set it to a simple random number plus session for WxApplication verification. api. sendReq (req );}

Add in AndroidManifest. xml, (android: exported = "true" must not be less)

<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 );
// The following Code determines whether WXEnteryActivity is returned after sharing. if handleIntent = false, IWXAPIEventHandler is not called, the transparent Activity needs to be destroyed here; 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; // The required code} switch (baseResp. errCode) {case BaseResp. errCode. ERR_ OK: Log. d (TAG, "onResp: Successful"); finish (); break; case BaseResp. errCode. ERR_USER_CANCEL: Log. d (TAG, "onResp: User canceled"); finish (); break; case BaseResp. errCode. ERR_AUTH_DENIED: Log. d (TAG, "onResp: request rejected"); finish (); break ;}}

Resp and code are defined as global variables. After the WXEntryWActivity page is destroyed, the onResume () method is used on the logon page to start other operations.

5.2 after obtaining the code, you can obtain the access_token through code on the logon page. The official website says: "access_token is the call credential for calling the authorization Link interface. Because the validity period of access_token (currently 2 hours) is short, when the access_token times out, you can use the refresh_token to refresh. "Therefore, after obtaining the access_token, you can request the refresh_token again. After refreshing the Token, you can get the access_token to send a request to obtain the user information;

Get access_token URL: AccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token? Appid = Your appid & secret = Your AppSecret & code = authorization obtained code & grant_type = authorization_code ";

Refresh access_token URL: Refresh_tokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token? Appid = Your appid & grant_type = refresh_token & refresh_token = access_token requested in the previous step;

Get user information URL: UserInfoUrl = "https://api.weixin.qq.com/sns/userinfo? Access_token = refreshed access_token & openid = The openid obtained when the access_token is refreshed;

@ Override protected void onResume () {Log. d (TAG, "onResume: 1"); super. onResume (); // The judgment here is to distinguish whether to destroy and restart from the WXEntryActivity page without the following code 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 () ;}}; // obtain access_token according to code, here, a post request 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 (); wechatlogtailkenmodel tokenModel = gson. fromJson (response, wechatlogtailkenmodel. class); refresh_token = tokenModel. getRefresh_token (); wxgetrefreshaccesen en () ;}, new Response. errorListener () {@ Override public void onErrorResponse (VolleyError error) {}}); request. setTag ("weChatGetToken"); XBLiveApplication. getHttpRequestQueue (). add (request);} // refresh access_token after receiving access_token, and get access_refresh and openid private void wxgetrefreshaccesen en () {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 (); wechatlogtailkenmodel tokenModel = gson. fromJson (response, wechatlogtailkenmodel. 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) ;}// obtain user information 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: Male; 0: female; 2: Unknown String province = userInfoModel. getProvince (); openId_WX = userInfoModel. getOpenid (); ToastUtils. toast ("Logon successful") ;}, new Response. errorListener () {@ Override public void onErrorResponse (VolleyError error ){}});
// The following code is registered by the volley framework. Ignore request. setTag ("weChatGetUserInfo"); XBLiveApplication. getHttpRequestQueue (). add (request );}

 

Note: During the test, the application signature must be consistent. For example, if you enter an application signature that does not have a packaging signature on the official website, the APP you tested does not have a packaging signature, there is no problem, but if you fill in the app signature that has been packaged and signed online on the official website, you must use the app with the package signature for testing.

Step 6: share with your friends:

 

Step 7: Share with friends:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.