有时候我们开发的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项目下载链接: