Learn android WeChat Logon (18) and android email logon 18

Source: Internet
Author: User
Tags openid

Logon to android (18) and logon to android (18)

Recently, I have joined the project to log on. The following describes how to log on to Alibaba Cloud and hope to help you.


Step 1:


Log on to the open platform and click "create application ":



A signature is required when an application is created. Download the signature tool:




After the application is created, two values are obtained: AppID and AppSecret. These two values are saved and will be used later.


Step 2:


For the downloaded SDK, select the Android open Toolkit:





Import -----> --------> to your project under the toolkit.


Step 3


Create a package in your project. Remember that the package name format must be the package name + wxapi in your project AndroidManifest. xml, as shown in

Last package name: net. sourceforge. simcpux. wxapi


Create a WXEntryActivity class under this package and define the callback method in this class:

Public class WXEntryActivity extends Activity implements IWXAPIEventHandler {private IWXAPI api; private BaseResp resp = null; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); api = wxapifacloud. createWXAPI (this, WX_APP_ID, false); api. handleIntent (getIntent (), this);} // when a request is sent to a third-party application, the method @ Overridepublic void onReq (BaseReq req) {finish ();} // process requests sent by third-party applications The response result is called back to the method @ Overridepublic void onResp (BaseResp resp) {String result = ""; if (resp! = Null) {resp = resp;} switch (resp. errCode) {case BaseResp. errCode. ERR_ OK: result = "sent successfully"; Toast. makeText (this, result, Toast. LENGTH_LONG ). show (); finish (); break; case BaseResp. errCode. ERR_USER_CANCEL: result = "cancel sending"; Toast. makeText (this, result, Toast. LENGTH_LONG ). show (); finish (); break; case BaseResp. errCode. ERR_AUTH_DENIED: result = "The message is rejected"; Toast. makeText (this, result, Toast. LENGTH_LONG ). show (); finish (); break; default: result = "send back"; Toast. makeText (this, result, Toast. LENGTH_LONG ). show (); finish (); break ;}@ Overrideprotected void onNewIntent (Intent intent) {super. onNewIntent (intent); setIntent (intent); api. handleIntent (intent, this); finish ();}}

In the preceding method, When you log on to the authorization page, click "authorize" and the onResp will be called back. A resp will be generated, and the code will be obtained through this resp. Use the following method:

(SendAuth.Resp) .code;

After obtaining the code, remember that this code is useful. The preceding WX_APP_ID is the AppID obtained when you create an application.


Then add the following code to the Activity of your project logon interface to implement the logon authorization interface. After you log on to the authorization system and return to your Activity, the onResume () life cycle of the Activity will be executed. Therefore, we recommend that you store the resp in the global variable in the preceding WXEntryActivity class.

Add the following methods to the logon Activity:

Public class MainLoginTest extends Activity {public static IWXAPI WXapi; private String weixinCode; private final static int LOGIN_WHAT_INIT = 1; private static String get_access_token = ""; // after obtaining the code in step 1, request the following link to get access_tokenpublic static String GetCodeRequest = "https://api.weixin.qq.com/sns/oauth2/access_token? Appid = APPID & secret = SECRET & code = CODE & grant_type = authorization_code "; // get user personal information public static String GetUserInfo =" https://api.weixin.qq.com/sns/userinfo? Access_token = ACCESS_TOKEN & openid = OPENID "; @ Overrideprotected void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stubsuper. onCreate (savedInstanceState);}/*** login */private void WXLogin () {WXapi = wxapifacloud. createWXAPI (this, WX_APP_ID, true); WXapi. registerApp (WX_APP_ID); SendAuth. req req = new SendAuth. req (); req. scope = "snsapi_userinfo"; req. state = "wechat_sdk_demo"; WXapi. sendR Eq (req) ;}@ Overrideprotected void onResume () {super. onResume ();/** resp is the */if (resp. getType () = ConstantsAPI. COMMAND_SENDAUTH) {// code returns weixinCode = (SendAuth. resp) resp ). code;/** splice the previous AppID, AppSecret, and code into a URL */get_access_token = getCodeRequest (weixinCode); Thread thread Thread = new thread (downloadRun); Thread. start (); try {thread. join ();} catch (InterruptedException e) {// TODO Auto-gener Ated catch blocke. printStackTrace () ;}}/ *** get the access_token URL () * @ param code for authorization, * @ return URL */public static String getCodeRequest (String code) {String result = null; GetCodeRequest = GetCodeRequest. replace ("APPID", urlEnodeUTF8 (AppConstants. WX_APP_ID); GetCodeRequest = GetCodeRequest. replace ("SECRET", urlEnodeUTF8 (AppConstants. WX_APP_SECRET); GetCodeRequest = GetCodeRequest. replace ("CODE ", UrlEnodeUTF8 (code); result = GetCodeRequest; return result;}/*** URL for Obtaining user personal information () * @ param access_token * @ param openid * @ return URL */public static String getUserInfo (String access_token, String openid) given when obtaining access_token) {String result = null; GetUserInfo = GetUserInfo. replace ("ACCESS_TOKEN", urlEnodeUTF8 (access_token); GetUserInfo = GetUserInfo. replace ("OPENID", urlEnodeUTF8 (openid) ); Result = GetUserInfo; return result;} public static String urlEnodeUTF8 (String str) {String result = str; try {result = URLEncoder. encode (str, "UTF-8");} catch (Exception e) {e. printStackTrace ();} return result;} public Runnable downloadRun = new Runnable () {@ Overridepublic void run () {WXGetAccessToken ();}}; /*** get access_token and so on () */private void wxgetaccesen en () {HttpClient get_access_token_http Client = new DefaultHttpClient (); HttpClient token = new DefaultHttpClient (); String access_token = ""; String openid = ""; try {HttpPost postMethod = new HttpPost (get_access_token ); httpResponse response = get_access_token_httpClient.execute (postMethod); // execute the POST method if (response. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {InputStream is = response. getEntity (). getContent (); Buff EredReader br = new BufferedReader (new InputStreamReader (is); String str = ""; StringBuffer sb = new StringBuffer (); while (str = br. readLine ())! = Null) {sb. append (str);} is. close (); String josn = sb. toString (); JSONObject json1 = new JSONObject (josn); access_token = (String) json1.get ("access_token"); openid = (String) json1.get ("openid ");} else {}} catch (UnsupportedEncodingException e) {e. printStackTrace ();} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} catch (JSONException e) {e. printSt AckTrace ();} String get_user_info_url = getUserInfo (access_token, openid); WXGetUserInfo (get_user_info_url );} /*** obtain user personal information * @ param get_user_info_url call URL */private void WXGetUserInfo (String get_user_info_url) {HttpClient response = new DefaultHttpClient (); String openid = ""; string nickname = ""; String headimgurl = ""; try {HttpGet getMethod = new HttpGet (get_user_info_url); HttpResponse re Response Se = get_access_token_httpClient.execute (getMethod); // execute the GET method if (response. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {InputStream is = response. getEntity (). getContent (); BufferedReader br = new BufferedReader (new InputStreamReader (is); String str = ""; StringBuffer sb = new StringBuffer (); while (str = br. readLine ())! = Null) {sb. append (str);} is. close (); String josn = sb. toString (); JSONObject json1 = new JSONObject (josn); openid = (String) json1.get ("openid"); nickname = (String) json1.get ("nickname "); headimgurl = (String) json1.get ("headimgurl");} else {}} catch (UnsupportedEncodingException e) {e. printStackTrace ();} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} catch (JSONException e) {e. printStackTrace ();}}}

Based on the above program, you can obtain user information, code, openid, and access_token.



Last step:

Add the following configuration code to AndroidManifest:

  <activity            android:name="net.sourceforge.simcpux.wxapi.WXEntryActivity"            android:configChanges="orientation|keyboardHidden"            android:exported="true"            android:launchMode="singleTop"            android:screenOrientation="portrait"            android:theme="@android:style/Theme.Translucent.NoTitleBar" >            <intent-filter>                <action android:name="android.intent.action.VIEW" >                </action>                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>


Log on now





Reprinted please indicate the source: http://blog.csdn.net/hai_qing_xu_kong/article/details/44041241 sentiment control _


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.