1. 程式人生 > >Android之QQ授權登入獲取使用者資訊

Android之QQ授權登入獲取使用者資訊

有時候我們開發的app需要方便使用者簡單登入,可以讓使用者使用自己的qq、微信、微博登入到我們自己開發的app。

今天就在這裡總結一下如何在自己的app中整合QQ授權登入獲取使用者資訊的功能。

首先我們開啟騰訊開發平臺這個網頁,點選---->移動應用---->建立應用,成功建立應用後,可以產生我們需要的App ID和App Key,如下圖所示:


然後我們需要下載Android-SDK-vxxx,下載完後解壓我們可以得到兩個jar包,和一個例子程式碼,這兩個jar包是我們需要匯入到自己app中的,它們的名字是:mta-sdk-1.6.2.jar、open_sdk_r5043.jar。

很重要的參考資料是網站上提供的API文件和解壓之後的Sample例子程式碼。

先來看一下demo效果:

      

接著我們開始整合,在AndroidManifest檔案中加入以下內容:

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.bear.qqlogin.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.tencent.tauth.AuthActivity"
            android:launchMode="singleTask"
            android:noHistory="true" >
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="1104732758" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.tencent.connect.common.AssistActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
    </application>

在主程式裡面實現登入和獲取使用者資訊,主要起作用的語句:

mTencent.login(MainActivity.this, scope, loginListener); //登入

userInfo = new UserInfo(MainActivity.this, mTencent.getQQToken()); //獲取使用者資訊
userInfo.getUserInfo(userInfoListener);

整體程式碼如下:

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

/**
 * 
 * 通過呼叫Tencent類的login函式發起登入/校驗登入態。 
 * 
 * 該API具有兩個作用:
 * (1)如果開發者沒有呼叫mTencent例項的setOpenId、setAccessToken API,
 * 		則該API執行正常的登入操作;
 * (2)如果開發者先呼叫mTencent例項的setOpenId、setAccessToken
 * 		API,則該API執行校驗登入態的操作。如果登入態有效,則返回成功給應用,
 * 		如果登入態失效,則會自動進入登入流程,將最新的登入態資料返回給應用
 * 
 * @author super bear
 * 
 */
public class MainActivity extends Activity {

	private static final String APPID = "1104732758";

	private EditText et1;
	private EditText et2;
	
	private Tencent mTencent; //qq主操作物件
	private IUiListener loginListener; //授權登入監聽器
	private IUiListener userInfoListener; //獲取使用者資訊監聽器
	private String scope; //獲取資訊的範圍引數
	private UserInfo userInfo; //qq使用者資訊

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setupViews();
		initData();
	}

	@Override
	protected void onDestroy() {
		if (mTencent != null) {
			//登出登入
			mTencent.logout(MainActivity.this);
		}
		super.onDestroy();
	}

	private void setupViews() {
		et1 = (EditText) findViewById(R.id.editText1);
		et2 = (EditText) findViewById(R.id.editText2);

		findViewById(R.id.button2).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				System.out.println("你點選了使用qq登入按鈕");
				login();
			}
		});
		
		findViewById(R.id.button3).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				System.out.println("開始獲取使用者資訊");
				userInfo = new UserInfo(MainActivity.this, mTencent.getQQToken());
				userInfo.getUserInfo(userInfoListener);
			}
		});
	}

	private void initData() {
		//初始化qq主操作物件
		mTencent = Tencent.createInstance(APPID, MainActivity.this);
		//要所有許可權,不然會再次申請增量許可權,這裡不要設定成get_user_info,add_t
		scope = "all";
		
		loginListener = new IUiListener() {

			@Override
			public void onError(UiError arg0) {
				// TODO Auto-generated method stub

			}

			/**
			 * 返回json資料樣例
			 * 
			 * {"ret":0,"pay_token":"D3D678728DC580FBCDE15722B72E7365",
			 * "pf":"desktop_m_qq-10000144-android-2002-",
			 * "query_authority_cost":448,
			 * "authority_cost":-136792089,
			 * "openid":"015A22DED93BD15E0E6B0DDB3E59DE2D",
			 * "expires_in":7776000,
			 * "pfkey":"6068ea1c4a716d4141bca0ddb3df1bb9",
			 * "msg":"",
			 * "access_token":"A2455F491478233529D0106D2CE6EB45",
			 * "login_cost":499}
			 */
			@Override
			public void onComplete(Object value) {
				// TODO Auto-generated method stub
				
				System.out.println("有資料返回..");
				if (value == null) {
					return;
				}

				try {
					JSONObject jo = (JSONObject) value;

					int ret = jo.getInt("ret");
					
					System.out.println("json=" + String.valueOf(jo));
					
					if (ret == 0) {
						Toast.makeText(MainActivity.this, "登入成功",
								Toast.LENGTH_LONG).show();

						String openID = jo.getString("openid");
						String accessToken = jo.getString("access_token");
						String expires = jo.getString("expires_in");
						mTencent.setOpenId(openID);
						mTencent.setAccessToken(accessToken, expires);
					}

				} catch (Exception e) {
					// TODO: handle exception
				}

			}

			@Override
			public void onCancel() {
				// TODO Auto-generated method stub

			}
		};
		
		userInfoListener = new IUiListener() {
			
			@Override
			public void onError(UiError arg0) {
				// TODO Auto-generated method stub
				
			}
			
			/**
			 * 返回使用者資訊樣例
			 * 
			 * {"is_yellow_year_vip":"0","ret":0,
			 * "figureurl_qq_1":"http:\/\/q.qlogo.cn\/qqapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/40",
			 * "figureurl_qq_2":"http:\/\/q.qlogo.cn\/qqapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/100",
			 * "nickname":"攀爬←蝸牛","yellow_vip_level":"0","is_lost":0,"msg":"",
			 * "city":"黃岡","
			 * figureurl_1":"http:\/\/qzapp.qlogo.cn\/qzapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/50",
			 * "vip":"0","level":"0",
			 * "figureurl_2":"http:\/\/qzapp.qlogo.cn\/qzapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/100",
			 * "province":"湖北",
			 * "is_yellow_vip":"0","gender":"男",
			 * "figureurl":"http:\/\/qzapp.qlogo.cn\/qzapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/30"}
			 */
			@Override
			public void onComplete(Object arg0) {
				// TODO Auto-generated method stub
				if(arg0 == null){
					return;
				}
				try {
					JSONObject jo = (JSONObject) arg0;
					int ret = jo.getInt("ret");
					System.out.println("json=" + String.valueOf(jo));
					String nickName = jo.getString("nickname");
					String gender = jo.getString("gender");

					Toast.makeText(MainActivity.this, "你好," + nickName,
							Toast.LENGTH_LONG).show();

				} catch (Exception e) {
					// TODO: handle exception
				}
				
				
			}
			
			@Override
			public void onCancel() {
				// TODO Auto-generated method stub
				
			}
		};
	}

	private void login() {
		//如果session無效,就開始登入
		if (!mTencent.isSessionValid()) {
			//開始qq授權登入
			mTencent.login(MainActivity.this, scope, loginListener);
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == Constants.REQUEST_API) {
			if (resultCode == Constants.RESULT_LOGIN) {
				Tencent.handleResultData(data, loginListener);
			}
			super.onActivityResult(requestCode, resultCode, data);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

整個android專案下載連結: