android third party login

Developing Android to Realize Tripartite Login of Microblog(1)

This article describes three ways to realize the tripartite login of microblog. In fact, they are three ways. But there is only one slight difference between them, that is, the method names invoked before entering the authorization page are different.

1. SSO single sign-on authorization, calling this method can only be achieved on the premise that you have installed the Sina Weibo APP on your mobile phone.

2. Web page login authorization, this method will jump out of a micro-blog login Web page, so as to achieve login.

3. all in one mode authorization, which will decide whether to use sso authorization or web authorization according to whether the mobile phone installs micro-blog client or not. If there is a micro-blog client installed, the micro-blog client authorization will be invoked, otherwise the Web page authorization will be invoked.

The following is the specific implementation process:

1. Authorization section (Obtaining an Oauth2AccessToken object in the code)

1. APP key and App secret are applied for on Sina Weibo Open Platform. The specific steps are omitted. It is not only to fill in some application information, but also very easy to apply for (the developer account of unregistered Sina may need to register an account first). Here is the interface after successful application.

2. Fill in the "Basic Information" directory in the interface above. Android Information such as package name (the package name of your project), Android signature (you need to download the signature tool to generate the corresponding signature of the project) and click Save

Then add the callback page ( under Advanced Information, and click Submit

If run test When login account is not registered application account, then you need to add test account under "test information", and then click Save

3. Download SDK address:

4. Create a new jniLibs folder (don't misspell) under the main folder of the project. Copy all the folders under the libs folder in SDK to the jnilib folder of the project. The Weibo SDK Core_3.1.4.jar package is introduced into the project.

5. Adding permissions

  1. <uses-permission android:name="android.permission.INTERNET" />  
  2.     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
  3.     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  

6. Create a new Constants class. (Where APP_KEY is replaced by your own APP key, and careful people may find that the authorization callback page we added above is the REDIRECT_URL here.)
  1. /** 
  2.  * This class defines the parameters needed for authorization of microblog. 
  3.  *  
  4.  * @author SINA 
  5.  * @since 2013-09-29 
  6.  */  
  7. public class Constants {  
  9.     /** Current DEMO application's APP_KEY, third-party application should replace the APP_KEY with its own APP_KEY.*/  
  10.     public static final String APP_KEY      = "78219253";  
  12.     /**  
  13.      * Currently, callback pages for DEMO applications can be used by third-party applications. 
  14.      *  
  15.      * <p> 
  16.      * Note: As regards authorized callback pages, they are not visible to users for mobile client applications, so defining what form will not affect them. 
  17.      * However, SDK authentication login cannot be used without a definition. 
  18.      * It is recommended to use the default callback page: 
  19.      * </p> 
  20.      */  
  21.     public static final String REDIRECT_URL = "";  
  23.     /** 
  24.      * Scope It is a parameter of authorize interface in OAuth2.0 authorization mechanism. Through Scope, the platform will open more microblogs 
  25.      * Core functions for developers, but also to enhance user privacy protection, enhance the user experience, users have rights in the new OAuth 2.0 authorization page 
  26.      * Choose the functions assigned to the application. 
  27.      *  
  28.      * Through Sina Weibo Open Platform - > Management Center - > My Application - > Interface Management Office, we can see what interfaces we have now. 
  29.      * Use permissions, advanced permissions need to be applied. 
  30.      *  
  31.      * Scope currently supports multiple Scope permissions to be passed in, separated by commas. 
  32.      *  
  33.      * For information on which OpenAPI s require permission applications, see 
  34.      * For Scope concepts and considerations, see 
  35.      */  
  36.     public static final String SCOPE =   
  37.             "email,direct_messages_read,direct_messages_write,"  
  38.             + "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"  
  39.             + "follow_app_official_microblog," + "invitation_write";  
  40. }  

7. Three objects are required in Java code

  1. /** 
  2.      * Note: SsoHandler works only if SDK supports SSO 
  3.      */  
  4.     private SsoHandler mSsoHandler;  
  6.     private AuthInfo mAuthInfo;  
  8.     /** 
  9.      * Encapsulated "access_token", "expires_in", "refresh_token" and provided their management functions for receiving information returned after successful authorization in the callback method. 
  10.      */  
  11.     private Oauth2AccessToken mAccessToken;  

Initialization object

  1. //When authorizing quickly, please do not pass in SCOPE, otherwise authorization may not succeed  
  2.         mAuthInfo = new AuthInfo(this, Constants.APP_KEY, Constants.REDIRECT_URL, Constants.SCOPE);  
  3.         mSsoHandler = new SsoHandler(this, mAuthInfo);  

8. Define an implementation class for WeiBoAuthListener, which is required regardless of the authorization method mentioned above.

  1. /** 
  2.      * Microblog Authentication Authorization Callback Class. 
  3.      * 1. SSO When authorizing, you need to call {@link onActivityResult} in {link onActivityResult} after {@link SsoHandler authorizeCallBack}. 
  4.      * The callback will only be executed. 
  5.      * 2. When non-SSO authorization is completed, the callback is executed. 
  6.      * When the authorization is successful, save the access_token, expires_in, uid and other information to Shared Preferences. 
  7.      */  
  8.     class AuthListener implements WeiboAuthListener {  
  10.         @Override  
  11.         public void onComplete(Bundle bundle) {  
  12. //            System.out.println("onComplete(Bundle values)  ------>  "  
  13. //                    + bundle.toString());  
  14.             // onComplete(Bundle values) ------>  
  15.             // Bundle[ {_weibo_transaction = 1469413517894,  
  16.             // access_token = 2.00a64JBGyY87OCfa7707a82fzincGB,  
  17.             // refresh_token = 2.00a64JBGyY87OC11c02519480EWT1g,  
  18.             // expires_in = 2651682,  
  19.             // _weibo_appPackage =,  
  20.             // = user 5513808278,  
  21.             //userName = user 5513808278,  
  22.             // uid = 5513808278,  
  23.             // = null} ]  
  26.             //Analysis of Token from Bundle  
  27.             mAccessToken = Oauth2AccessToken.parseAccessToken(bundle);  
  28. //            System.out.println("onComplete  mAccessToken  ------>  "  
  29. //                    + mAccessToken.toString());  
  30.             // onComplete mAccessToken ------>  
  31.             // uid: 5513808278,  
  32.             // access_token: 2.00a64JBGyY87OCfa7707a82fzincGB,  
  33.             // refresh_token: 2.00a64JBGyY87OC11c02519480EWT1g,  
  34.             // phone_num: ,  
  35.             // expires_in: 1472065200534  
  37.             if (mAccessToken.isSessionValid()) {//Authorized success  
  38.                 Toast.makeText(MainActivity.this"Landing successfully", Toast.LENGTH_SHORT).show();  
  39.                 //Display Access_Token  
  40.                 tvAccessToken.setText("Access_token:\n" + mAccessToken.getToken());  
  41.                 //Getting User Specific Information  
  42. //                getUserInfo();  
  43.             } else {  
  44.                 /** 
  45.                  *  In the following cases, you will receive Code: 
  46.                  * 1. When you have not registered the package name and signature of the application on the platform; 
  47.                  * 2. When your registered application package name and signature are incorrect; 
  48.                  * 3. When the package name and signature registered on the platform does not match the package name and signature of the application you are currently testing. 
  49.                  */  
  50.                 String code = bundle.getString("code");//Get it directly from bundle s  
  51.                 if (!TextUtils.isEmpty(code)) {  
  52.                     Toast.makeText(MainActivity.this"Incorrect signature", Toast.LENGTH_SHORT).show();  
  53.                 }  
  54.             }  
  55. //String phoneNum = mAccessToken.getPhoneNum(); // It can be obtained when authorized to log in via SMS. This demo does not implement this authorization method.  
  56.         }  
  58.         @Override  
  59.         public void onWeiboException(WeiboException e) {  
  60.             Toast.makeText(MainActivity.this"Authorization exception", Toast.LENGTH_SHORT).show();  
  61.         }  
  63.         @Override  
  64.         public void onCancel() {  
  65.             Toast.makeText(MainActivity.this"Authorization cancelled", Toast.LENGTH_SHORT).show();  
  66.         }  
  67.     }  

9. The following are the methods invoked by various authorization modes (as you can see, the main difference among the three login modes is that the ssohandler object invocation method is different).

  1. /** 
  2.      * all in one Mode Authorization, Automatic Detection 
  3.      */  
  4.         mSsoHandler.authorize(new AuthListener());  
  7.     /** 
  8.      * Web To grant authorization 
  9.      */  
  11.         mSsoHandler.authorizeWeb(new AuthListener());  
  14.     /** 
  15.      * SSO Authorization, client only 
  16.      */  
  18.         mSsoHandler.authorizeClientSso(new AuthListener());  

Note: If you are using web authorization, you need to declare the following activities in Android Manifest. XML

  1. <!--micro-blog Web When authorizing, you need to register the authorization interface-->  
  2.         <activity  
  3.             android:name=""  
  4.             android:configChanges="keyboardHidden|orientation"  
  5.             android:exported="false"  
  6.             android:windowSoftInputMode="adjustResize"></activity>  

10. An easy step to take, rewrite the onActivityResult method, or you won't be able to call back the method

  1. @Override  
  2.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  3.         super.onActivityResult(requestCode, resultCode, data);  
  5.         //SSO Authorization Callback  
  6.         //Important: The activity that initiates sso login must rewrite onActivty Results  
  7.         if (mSsoHandler != null) {  
  8.             mSsoHandler.authorizeCallBack(requestCode, resultCode, data);  
  9.         }  
  10.     }  

In this way, the authorization part is fully implemented.

2. Obtain the basic information of the user (Obtain the basic information of the user through the Oauth2AccessToken object obtained above)

11. To get information, weibosdk in SDK should be introduced into the project as a library (I quoted its jar package directly, which proved to be possible).

Declare a variable first

  1. //Interface for obtaining user information (need to introduce the official weibosdk library into the project first)  
  2.     private UsersAPI mUsersAPI;  

Then getUserInfo() is removed from the onComplete callback method of weiboAuthListener above; the comment on that code is removed. The getUserInfo() method is implemented as follows.

  1. /** 
  2.      * Getting User Personal Information 
  3.      */  
  4.     private void getUserInfo() {  
  5.         //Getting User Information Interface  
  6.         mUsersAPI = new UsersAPI(MainActivity.this, Constants.APP_KEY, mAccessToken);  
  7.         System.out.println("mUsersAPI  ----->   " + mUsersAPI.toString());  
  9.         //Calling interface  
  10.         long uid = Long.parseLong(mAccessToken.getUid());  
  11.         System.out.println("--------------uid-------------->    " + uid);  
  12., mListener);//Pass the uid to listener and receive the user's personal information in json format through uid in the listener callback  
  13.     }  
  14.     /** 
  15.      * Implement asynchronous request interface callback and parse User information directly in callback 
  16.      */  
  17.     private RequestListener mListener = new RequestListener() {  
  18.         @Override  
  19.         public void onComplete(String response) {  
  20.             if (!TextUtils.isEmpty(response)) {  
  21.                 //Call User parse to parse JSON strings into User objects  
  22.                 User user = User.parse(response);  
  23.                 String nickName = user.screen_name;  
  24.                 tvNickName.setText("User nicknames: " + user.screen_name);  
  25.                 tvGender.setText("User gender: " + user.gender);  
  26.                 tvLocation.setText("User location: " + user.location);  
  27. //Toast.makeText(LogInActivity.this,'User's nickname: +nickName, Toast.LENGTH_SHORT).show();  
  28.             }  
  29.         }  
  31.         /** 
  32.          *If the logged-in account is not the registered application account when running the test, then you need to go: 
  33.          *Open Platform -"Management Center -" Application Information -"Test Information -" Add a test account (fill in the user nickname)! 
  34.          * Otherwise, the following exception will be thrown 
  35.          */  
  36.         @Override  
  37.         public void onWeiboException(WeiboException e) {  
  38.             e.printStackTrace();  
  39.             Toast.makeText(MainActivity.this"Getting User Personal Information Abnormal", Toast.LENGTH_SHORT).show();  
  40.         }  
  41.     };  

In this way, we can get the basic information of users!

Information in the User class can be consulted:

This demo is completed with reference to Word documents 6.1 and 7.1 under the New Documents folder in SDK.

Demo Download Address:

Developing Android to Realize Tripartite Login of Microblog(2)

Friends who have done third-party login on Sina Weibo know that their official documents are really bad, and adding new applications is also troublesome. I also read the document, while looking at demo, scrambling to achieve third-party login function. Today I share with you a complete development process, from the application developer account, to the integration of SDK, to code writing. ps: The SDK version I used was Weibo SDK Core_3.1.2

Step 1: Apply for Developer Account, Official Website

Log in or register Sina Weibo account

Then create a new application. When you create it, you should pay attention to several points:

Get APPID, my application - > application information - > basic information

My Application - > Application Information - > Basic Information

The package name refers to the contents of the package attribute in the AndroidManifest.xml file.

Signatures must be generated through the official MD5 signature tool, but Baidu Search, I also have a link here.

It's about this long. Just fill in the Android signature column on the official website against the signature.

Click on my application - > application information - > advanced information, and fill in the callback address. This is the address that will be invoked after the authorization is successful. It will be used in subsequent coding. It must be consistent. You can use

Add a test account.

Step 2: Integrating SDK,

Download the latest SDK files on the official website.

Or use what I've provided here.

Copy six folders under the directory weibo_android_sdk-master libs to the libs file of the project.

Copy Weibo SDK Core_3.1.2.jar to libs file under weibo_android_sdk-master directory

Then select weiboSDK Core_3.1.2. jar, right-click Build Path - > Add to Build Path

So far, the integration has been half successful.

Modify the AndroidManifest.xml file and add the following code

            android:windowSoftInputMode="adjustResize" >

            android:exported="false" >

Add permissions:

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

So SDK is integrated.

Step 3: Coding

I mainly refer to the official demo to write, the key is three java files

LoginActivity, which centrally calls the class of Sina Weibo API, realizes the functions of third party authorization, login, exit and display user information when login.

package com.example.thirdpartyloginafc;

import java.text.SimpleDateFormat;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class LoginActivity extends Activity implements OnClickListener {

	private AuthInfo mAuthInfo;
	private Button btnweibo;
	private Button btnlogout;
	private TextView tv;
	private String nickname="";

	/** Encapsulated "access_token", "expires_in", "refresh_token" and provided their management functions.*/
	private Oauth2AccessToken mAccessToken;

	/** Note: SsoHandler is valid only if SDK supports SSO.*/
	private SsoHandler mSsoHandler;

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub


	private void initData() {
		// TODO Auto-generated method stub
		//Read the last saved AccessToken and other information from Shared Preferences.
		//AccessToken is not available when this application is first launched
		mAccessToken = AccessTokenKeeper.readAccessToken(this);
		if (mAccessToken.isSessionValid()) {

	private void initViews() {

		btnweibo = (Button) findViewById(;
		btnlogout = (Button) findViewById(;
		tv = (TextView) findViewById(;
		//Get Token View and make the content of the prompt View scrollable (small screen may not be fully displayed)
		tv.setMovementMethod(new ScrollingMovementMethod());

	private void initEvents() {


	 * Initialization of Microblog Authorization
	private void initweibologin() {
		// TODO Auto-generated method stub
		//Initialize authorization class objects and save application information
		mAuthInfo = new AuthInfo(this, Constants.APP_KEY,
				Constants.REDIRECT_URL, Constants.SCOPE);
		mSsoHandler = new SsoHandler(LoginActivity.this, mAuthInfo);


	 * When SSO authorizes Activity to exit, the function is called.
	 * @see {@link Activity#onActivityResult}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		//SSO Authorized Callback
		//Important: Activity that initiates SSO landing must rewrite onActivityResults
		if (mSsoHandler != null) {
			mSsoHandler.authorizeCallBack(requestCode, resultCode, data);


	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case Authorization, ALL IN ONE
									//If a microblog client is installed on the mobile phone, client authorization is used, and if not, web authorization is used.
			mSsoHandler.authorize(new AuthListener());

		case logout
			nickname = "";
			mAccessToken = new Oauth2AccessToken();

	 * Microblog Authentication Authorization Callback Class. 1. SSO authorization requires{@link #onActivityResult} Call in
	 * {@link SsoHandler#authorizeCallBack} After that, the callback will be executed. 2. Non-SSO
	 * When authorization ends, the callback is executed. When the authorization is successful, please save the access_token, expires_in, uid and other information to
	 * SharedPreferences Medium.
	class AuthListener implements WeiboAuthListener {

		public void onCancel() {
			// TODO Auto-generated method stub
			Toast.makeText(LoginActivity.this"Cancellation of authorization", Toast.LENGTH_LONG)

		public void onComplete(Bundle values) {
			// TODO Auto-generated method stub
			//Analysis of Token from Bundle
			mAccessToken = Oauth2AccessToken.parseAccessToken(values);
			if (mAccessToken.isSessionValid()) {
				nickname = "User name:"
						+ String.valueOf(values
				//Display Token

				//Save Token to Shared Preferences
				Toast.makeText(LoginActivity.this"Authorized success", Toast.LENGTH_SHORT)
				// Toast.makeText(
				// LoginActivity.this,
				//"Head Address:"
				// + String.valueOf(values
				// .get("")),
				// Toast.LENGTH_LONG).show();

				Toast.makeText(LoginActivity.this, nickname, Toast.LENGTH_LONG)

			} else {
				//In the following cases, you will receive Code:
				//1. When you have not registered the package name and signature of the application on the platform;
				//2. When your registered application package name and signature are incorrect;
				//3. When the package name and signature registered on the platform do not match the package name and signature of the application you are currently testing.
				String code = values.getString("code");
				String message = "privilege grant failed";
				if (!TextUtils.isEmpty(code)) {
					message = message + "\nObtained the code: " + code;
				Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG)

		public void onWeiboException(WeiboException e) {
			// TODO Auto-generated method stub
					"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)


	 * Display current Token information.
	 * @param hasExisted
	 *            Whether token information already exists in the configuration file and is legal
	private void updateTokenView(boolean hasExisted) {
		String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
				.format(new java.util.Date(mAccessToken.getExpiresTime()));
		String format = getString(R.string.weibosdk_demo_token_to_string_format_1);
		tv.setText(String.format(format, mAccessToken.getToken(), date));

		String message = String.format(format, mAccessToken.getToken(), date);
		if (hasExisted) {
			message = getString(R.string.weibosdk_demo_token_has_existed)
					+ "\n" + message;

		message += "\n" + nickname;


package com.example.thirdpartyloginafc;

 * Copyright (C) 2010-2013 The SINA WEIBO Open Source Project
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * See the License for the specific language governing permissions and
 * limitations under the License.

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;


 * This class defines the parameters needed for authorization of microblog.
 * @author SINA
 * @since 2013-10-07
public class AccessTokenKeeper {
	private static final String PREFERENCES_NAME = "com_weibo_sdk_android";

	private static final String KEY_UID = "uid";
	private static final String KEY_ACCESS_TOKEN = "access_token";
	private static final String KEY_EXPIRES_IN = "expires_in";
	private static final String KEY_REFRESH_TOKEN = "refresh_token";

	 * Save the Token object to SharedPreferences.
	 * @param context
	 *            Application context environment
	 * @param token
	 *            Token object
	public static void writeAccessToken(Context context, Oauth2AccessToken token) {
		if (null == context || null == token) {

		SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME,
		Editor editor = pref.edit();
		editor.putString(KEY_UID, token.getUid());
		editor.putString(KEY_ACCESS_TOKEN, token.getToken());
		editor.putString(KEY_REFRESH_TOKEN, token.getRefreshToken());
		editor.putLong(KEY_EXPIRES_IN, token.getExpiresTime());

	 * Read Token information from Shared Preferences.
	 * @param context
	 *            Application context environment
	 * @return Return Token object
	public static Oauth2AccessToken readAccessToken(Context context) {
		if (null == context) {
			return null;

		Oauth2AccessToken token = new Oauth2AccessToken();
		SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME,
		token.setUid(pref.getString(KEY_UID, ""));
		token.setToken(pref.getString(KEY_ACCESS_TOKEN, ""));
		token.setRefreshToken(pref.getString(KEY_REFRESH_TOKEN, ""));
		token.setExpiresTime(pref.getLong(KEY_EXPIRES_IN, 0));

		return token;

	 * Empty Token information in Shared Preferences.
	 * @param context
	 *            Application context environment
	public static void clear(Context context) {
		if (null == context) {

		SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME,
		Editor editor = pref.edit();

package com.example.thirdpartyloginafc;

public class Constants {
	public static final String APP_KEY = "Own id";
	public static final String REDIRECT_URL = "Callback address corresponding to web page;
	public static final String SCOPE = "email,direct_messages_read,direct_messages_write,"
			+ "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
			+ "follow_app_official_microblog," + "invitation_write";


Operation result

Authorized success

Officially, there are three ways of login, the first is through the client, the second is through the web, the third is to try to login through the client, if there is no client installed, then through the web, the third way is used here.

The code for this example:

After importing the project, remember to modify the APP_KEY and REDIRECT_URL in Constants. If you have any questions, please communicate!!

Development of sdk and Address of Development Help Documents on Microblog

Android implements QQ third party login

Android Implementing QQ third party login

QQ third-party login is needed in the project. After some efforts, it has been written out. Now summarize the following, in order to avoid forgetting later, it would be better to help other children's shoes.

The first thing is to download SDK and DEMO. Download

This article is my own integrated simple DEMO.

Let's look at the picture first.

Principle: We need to use QQ to login our application, not without registration, but we are registering for users in the background, but users do not know that registration needs a unique identity, the combination of letters and numbers above is the only identity we want to obtain: OpenID.

Follow the code.

First, we'll load the open_sdk.jar and mta-sdk-1.00.jar packages. By the way, let's look at the classes I've used altogether.

Among them, AppConstant is used to place the APPID, because other third-party logins may be introduced to facilitate management, so create such a class. Util is a processing class that retrieves pictures from the Internet according to the path


Well, get to the point.

First, two definitions in AndroidManifest.xml are not possible if they are not defined

01.<activity"com.tencent.tauth.AuthActivity""singleTask""true" >
06.<action android:name="android.intent.action.VIEW" />
08.<category android:name="android.intent.category.DEFAULT" />
09.<category android:name="android.intent.category.BROWSABLE" />
11.<data Android: scheme = "tencent2222" /> <! - Note that you replace 22222222 with your appid here - > <
14.<activity android:name="com.tencent.connect.common.AssistActivity""@android:style/Theme.Translucent.NoTitleBar""portrait"/>


Then there are two permissions

1.<uses-permission android:name="android.permission.INTERNET" />
2.<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


Next is the layout file, activity_main.xml login button, to get the textview of the avatar, nickname, openid

01.<LinearLayout xmlns:android="""fill_parent""fill_parent""vertical">
06.<Button"@+id/login""fill_parent""wrap_content" "login"/>


Then MainActivity

01.public class MainActivity extends Activity implements OnClickListener {
02.TextView openidTextView;
03.TextView nicknameTextView;
04.Button loginButton;
05.ImageView userlogo;
06.private Tencent mTencent;
07.public static QQAuth mQQAuth;
08.public static String mAppid;
09.public static String openidString;
10.public static String nicknameString;
11.public static String TAG="MainActivity";
12.Bitmap bitmap = null;
14.public void onCreate(Bundle savedInstanceState) {
17. // Button for login
20. // textView used to display OpenID
22. // textview used to display nicknames
24. // Imageview for displaying avatars
28.public void onClick(View v) {
29.// TODO Auto-generated method stub
30.switch (v.getId()) {
39. // Here is the key code for calling QQ login
40.public void LoginQQ() {
41. // Here's the APP_ID for your application. I'm using the official test APP_ID in DEMO. 222222
42.mAppid = AppConstant.APP_ID;
43. // The first parameter is the APID of the application mentioned above, and the second is the global Context, which implements the call to QQ login.
44.mTencent = Tencent.createInstance(mAppid,getApplicationContext());
45. /** Through this code, SDK implements QQ login. This method has three parameters, the first parameter is context context, and the second parameter is SCOPO. Is a String type string that represents some permissions
46. Description in official documents: What API privileges an application needs to obtain, separated by ",". For example: SCOPE = "get_user_info,add_t"; all permissions are "all"
47. The third parameter is an instance of the IUiListener interface, an event listener, using the implementation class of the interface. */
48.mTencent.login(MainActivity.this,"all", new BaseUiListener());
51. /** When a custom listener implements the IUiListener interface, it must implement three methods of the interface.
52.* onComplete  onCancel onError
53. * Indicates that third party login is successful and cancelled respectively. Mistake. * /
54.private class BaseUiListener implements IUiListener {
56.public void onCancel() {
57.// TODO Auto-generated method stub
60.public void onComplete(Object response) {
61.// TODO Auto-generated method stub
62. Toast. makeText (get Application Context (), "Log in Successfully", 0).show();
63.try {
64. // Get data in JSON format, get what you want.
65. // If you don't know what you can get, take a look at the following LOG
66.Log.e(TAG, "-------------"+response.toString());
67.openidString = ((JSONObject) response).getString("openid");
69.Log.e(TAG, "-------------"+openidString);
70.//access_token= ((JSONObject) response).getString("access_token");              //expires_in = ((JSONObject) response).getString("expires_in");
71.} catch (JSONException e) {
72.// TODO Auto-generated catch block
75. /** So far, you've got OpneID and other content you want to get.
76.QQ login success, we also want to get some basic information about QQ, such as nicknames, avatars, what to do at this time?
77.sdk provides us with a class UserInfo, which encapsulates some information about QQ users. We can get this information through this class.
78. How do I get this UserInfo class?   */
79.Q<a href="" target="_blank" class="keylink">QT</a>oken qqToken = mTencent.getQ<a href=""target="_blank" class="keylink">QT</a>oken();
80.UserInfo info = new UserInfo(getApplicationContext(), <a href="" target="_blank" class="keylink">qq</a>Token);
81. // So we'll get this class, and then we'll do the same thing as above, parsing JSON as well. IUiListener() {
03.public void onComplete(final Object response) {
04.// TODO Auto-generated method stub
05.Log.e(TAG, "---------------111111");
06.Message msg = new Message();
07.msg.obj = response;
08.msg.what = 0;
10.Log.e(TAG, "-----111---"+response.toString());
11. /** Threads are used here because pictures need to be downloaded, if you want to get other text information directly.
12.* Operating in mHandler
14.*/ Thread(){
18.public void run() {
19.// TODO Auto-generated method stub
20.JSONObject json = (JSONObject)response;
21.try {
22.bitmap = Util.getbitmap(json.getString("figureurl_<a href="" target="_blank" class="keylink">qq</a>_2"));
23.} catch (JSONException e) {
24.// TODO Auto-generated catch block
27.Message msg = new Message();
28.msg.obj = bitmap;
29.msg.what = 1;
34.public void onCancel() {
35.Log.e(TAG, "--------------111112");
36.// TODO Auto-generated method stub                 
38.public void onError(UiError arg0) {
39.// TODO Auto-generated method stub
40.Log.e(TAG, "-111113"+":"+arg0);
47.public void onError(UiError arg0) {
48.// TODO Auto-generated method stub
53.Handler mHandler = new Handler() {
56.public void handleMessage(Message msg) {
57.if (msg.what == 0) {
58.JSONObject response = (JSONObject) msg.obj;
59.if (response.has("nickname")) {
60.try {
64.Log.e(TAG, "--"+nicknameString);
65.} catch (JSONException e) {
66.// TODO Auto-generated catch block
70.}else if(msg.what == 1){
71.Bitmap bitmap = (Bitmap)msg.obj;

The figure above shows the return LOG of login Q

Above is our LOG returned from UserInfo provided by Tencent.

Then AppConstant. Java

1.public class AppConstant {
2.public static String APP_ID="222222";


01.public class Util {
02.public static String TAG="UTIL";
03.public static Bitmap getbitmap(String imageUri) {
04.Log.v(TAG, "getbitmap:" + imageUri);
05.// Display pictures on the network
06.Bitmap bitmap = null;
07.try {
08.URL myFileUrl = new URL(imageUri);
09.HttpURLConnection conn = (HttpURLConnection) myFileUrl
13.InputStream is = conn.getInputStream();
14.bitmap = BitmapFactory.decodeStream(is);;
17.Log.v(TAG, "image download finished." + imageUri);
18.} catch (IOException e) {
20.Log.v(TAG, "getbitmap bmp fail---");
21.return null;
23.return bitmap;


Here's all the code. We get OpenID, which is the key to the unique identity. Then we can see what information is needed for the interface that needs to be logged on in the project to get it.

qq official document reference and Configure Engineering instances and implement callbacks login and logout

Http:// download address

Android Wechat Third Party Login

These two days, it solved the problem of authorized login of the third party of Wechat. As a novice, it is also a bitter tear to think about. I think, I will share with you the pit I encountered, so that novices can avoid such problems as mine smoothly.

Step 1 Wechat Developer Platform

The solution I started with was to go. Wechat Developer Platform Look at the API documentation.

The main meaning of this API document is three points:

1. You have to download these things.( Download links One is his sample code and the other is his signature generation tool.

2. If your own APP wants to be authorized by the third party of Wechat, you have to apply for an APPID, which is a code assigned to us by Wechat. Of course, Wechat is not a free service for you. In order to get this third-party authorized function, you have to pay 300 yuan to Wechat. After applying for this authorization, you need to fill in an application package name and an application signature.

Application package name

Application signature

Use the signature generation tool, enter the package name, and query the application signature


3. Then open DEMO

WXEntry Activity is our most important concern.

// When a wechat sends a request to a third party application, it calls back to this method.
public void onReq(BaseReq req) {
    // TODO

This onResp method is automatically invoked when you click on the authorized login interface, so we can get the required token from it. Note that andorid is called token, ios is called code, not because of the sdk version, which needs to be noted.

// The response of a third-party application to a request sent to Wechat after processing is called back to this method.
public void onResp(BaseResp resp) {
    int result = 0;
    switch (resp.errCode) {
        case BaseResp.ErrCode.ERR_OK:
            result = R.string.errcode_success;
/* Get token*/
            SendAuth.Resp sendResp = (SendAuth.Resp) resp;
            String code = sendResp.token;
            Log.d("Tag", "code\t" + code);
        case BaseResp.ErrCode.ERR_USER_CANCEL:
            result = R.string.errcode_cancel;
        case BaseResp.ErrCode.ERR_AUTH_DENIED:
            result = R.string.errcode_deny;
            result = R.string.errcode_unknown;

Replace APP_ID with a legitimate appId for your application from the official website

public class Constants {
    // Replace APP_ID with a legitimate appId for your application from the official website
    public static final String APP_ID = "wx77777";


// IWX API is an open API interface for third-party app and wechat Communications
private IWXAPI api;
final SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = "wechat_sdk_demo_test";
// Send Authorized Landing Request

This step is to ask for code with Wechat. After executing this code. Wechat calls the onResp() method in the WXEntityActivity class just now. And return the code. See the code above. After you get the code, you can get access_token through the code.  

Request the following link for access_token:

This step and Wechat communication access_token is the normal access link. Use httpClient instead of onReq(), the way to communicate with Wechat as mentioned in the Access Guide, and then use access_token. You can call the interface to get the user's basic information. The access guide for specific return parameters and what is said is very clear. So far, the authorization of Wechat has been basically successful.

Here, we will add Custom debug keystore. The debug keystore above will not communicate with Wechat.

And the keystore we added also meets some specifications, so we need to change it.

But pay attention to debug keystore in the development process.

Step 2 How Android studio generates keystore files

The first step is to create a signature file

Step 2 Fill in the Signature Parameters

The third step is to select the type of construction

Step 4 View Generating the apk file

Step 3 How Android studio locates keystore files

When running Weichat Sharing Demo and Sina Weibo Sharing Demo, debug.keystore in Demo needs to be modified to run authorization and sharing.

In Android development, the tools used are Eclispse and Android Studio. Among them, the use of Eclipse to modify the debug.keystore way Sina Weibo documents are introduced, in Eclipse click "Windows - > Preferences - > Android - > Build", in the right "Custom debug keystore" to select the Demo debug.keystore.

The approach in Android Studio is the application module of Modules in Project Structure. Then select Signing, click on the "+" number, call it "debug", and in "Store File", select debug.keystore in Demo, as shown below.

Then select "Build Types" in "Signing Config" in "debug" and select "debug" as configured above, as shown below.

Click "OK" and recompile it.

After the above configuration is completed, it will automatically be generated in android {} in build.gradle in the project module.

signingConfigs {
    debug {
StorFile file('.keystore file path')

And generated in buildTypes

debug {
    signingConfig signingConfigs.debug

Of course, you can write the above configuration in build.gradle without the interface configuration, and it's OK too.

Step 4 Get the signature and fill it in on the Wechat Developer Platform

Next, the project located in the jks file is burned and written into the program, and then the MD code of the signature tool is filled in to the Wechat Developer Platform, and the third party authorization can be invoked to login.


Effectiveness Map ___________


Reference link:

Wechat Authorized Login to Access Third Party App (Step Summary) Android

Android Studio modifies debug.keystore

Android Studio Signature Packing Process Diagram

Need to refer to the following website: android access to Wechat

Mobile Application Wechat Login Development Guide

Authorized post-interface invocation (UnionID)

Tags: Android SDK Mobile Java

Posted on Tue, 02 Apr 2019 17:03:29 -0400 by dg