腾讯QQ第三方登陆

因为做的项目有这个需要,所以做了一个腾讯QQ第三方登陆(我的编码格式是UTF-8).

这里是SDK下载.使用的sdk版本:V2.2(更新日期:2014-1-21

这个可以获取昵称,头像.如果有其他需要,可以去看腾讯的移动应用接入

贴出项目结构图:


在下载的sdk的lib文件夹找到open_sdk.jar和mta_sdk_xxx.jar文件,然后复制到项目的libs里面.

然后是配置清单文件中:

1.添加两个权限

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

2.添加activity(是在application里面的原有代码上直接添加以下代码)

<!-- 添加的活动 -->
        <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="tencent222222" /> <!-- QQ第三方登陆AppId 可换成自己的appid.腾讯给的默认测试ID是: 222222 -->  
            </intent-filter>  
        </activity>  
        <activity  
            android:name="com.tencent.connect.common.AssistActivity"  
            android:screenOrientation="portrait"  
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />  
        


再贴上简单的布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- 昵称 -->
    <TextView
        android:id="@+id/user_nickname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="昵称" />

    <!-- 头像 -->
    <ImageView
        android:id="@+id/user_logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <!-- 点击登陆按钮	 -->
    <Button
        android:id="@+id/new_login_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录" />

    <!-- 返回信息 -->
    <TextView
        android:id="@+id/user_callback"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="返回消息" />

</LinearLayout>

最后就是重点了java代码,我就直接贴上,不吊胃口了,

package com.tencent.tauth;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQAuth;
import com.tencent.tauth.authactivity.R;

public class TestQQ extends Activity {
	
	/** 用户昵称*/
	private TextView mUserInfo;
	
	/** 用户头像*/
	private ImageView mUserLogo;
	
	/** 第三方登陆点击按钮*/
	private Button mNewLoginButton;
	
	/** 用户昵称*/
	private TextView backInfo;
	
	/** 用户信息*/
	private UserInfo mInfo;
	
	/** Tencent类是SDK的主要实现类,开发者可通过Tencent类访问腾讯开放的OpenAPI。*/
	private Tencent mTencent;
	
	/** */
	private QQAuth mQQAuth;
	
	/** 其中mAppId是分配给第三方应用的appid,类型为String。*/
	public String mAppId = "222222";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		initView();
	}
	
	/**
	 * 初始化
	 */
	private void initView() {
		
		mUserInfo = (TextView) findViewById(R.id.user_nickname);
		mUserLogo = (ImageView) findViewById(R.id.user_logo);
		mNewLoginButton = (Button) findViewById(R.id.new_login_btn);
		mNewLoginButton.setOnClickListener(clickListener);
		
		backInfo = (TextView) findViewById(R.id.user_callback);
		
		// 1.4版本:此处需新增参数,传入应用程序的全局context,可通过activity的getApplicationContext方法获取
		mQQAuth = QQAuth.createInstance(mAppId, this.getApplicationContext());
		//实例化
		mTencent = Tencent.createInstance(mAppId, this);
		
	}

	
	/**
	 * 点击开始第三方登陆
	 */
	public OnClickListener clickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
//			// 是否支持sso登录  
//            if (mTencent.isSupportSSOLogin(this)) {  
//                onClickLogin();  
//            }
			onClickLogin();
		}
	};
	
	/**
	 * 登陆
	 */
	public void onClickLogin(){
		//登陆
		if(!mQQAuth.isSessionValid()){
			IUiListener listener = new BaseUiListener(){

				@Override
				protected void doComplete(JSONObject values) {
					super.doComplete(values);
					//更新用户信息
					updateUserInfo();
					if(mQQAuth != null){
						mNewLoginButton.setText("登陆");
						mNewLoginButton.setTextColor(Color.parseColor("#0079FF"));
					}
				}
			};
		//"all"所有的权限 , listener 回调的实例
		//mQQAuth.login(this,"all",listener);
	         // 这版本登录是使用的这种方式,后面的几个参数是啥意思 我也没查到  
                 mTencent.loginWithOEM(this, "all", listener, "10000144","10000144", "xxxx"); 
		} else {
			//注销登陆
			mQQAuth.logout(this);
			updateUserInfo();
			
			//updateLoginButton();
			mNewLoginButton.setText("退出登录");
			mNewLoginButton.setTextColor(Color.parseColor("#FF0005"));
		}
	}
	
	
	
	/**
	 * 调用sdk封装好的接口,需要传入回调的实例,会返回服务器的消息
	 */
	private class BaseUiListener implements IUiListener{

		/**
		 * 取消
		 */
		@Override
		public void onCancel() {
			Toast.makeText(TestQQ.this, "取消", Toast.LENGTH_SHORT).show();
		}

		/**
		 * 成功
		 */
		@Override
		public void onComplete(Object response) {
                        //获得返回信息
			backInfo.setText(response.toString());
			doComplete((JSONObject) response);
		}

		/**
		 * 
		 */
		@Override
		public void onError(UiError e) {
			Toast.makeText(TestQQ.this, e.toString(), Toast.LENGTH_SHORT).show();
		}
		
		/**  
         * 处理返回的消息 比如把json转换为对象什么的  
         *   
         * @param values  
         */  
        protected void doComplete(JSONObject values) {  
  
        } 
		
	}
	
	
	
    /** */
	Handler mHandler = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			if(msg.what == 0){
				mUserInfo.setVisibility(android.view.View.VISIBLE);
				mUserInfo.setText(msg.getData().getString("nickname"));
			}else if(msg.what == 1){
				Bitmap bitmap = (Bitmap) msg.obj;
				mUserLogo.setImageBitmap(bitmap);
				mUserLogo.setVisibility(android.view.View.VISIBLE);
			}
		};
	};
	
	/**
	 * 更新用户信息
	 */
	private void updateUserInfo(){
		if(mQQAuth != null && mQQAuth.isSessionValid()){
			IUiListener iUiListener = new IUiListener() {
				
				@Override
				public void onError(UiError e) {
					
				}
				
				@Override
				public void onComplete(Object response) {
					JSONObject json = (JSONObject) response;
					
					/** 昵称*/
					Message msg = new Message();
					String nickname = null;
					try {
						nickname = ((JSONObject) response).getString("nickname");
					} catch (JSONException e) {
						e.printStackTrace();
					}  
					//将数据插曲key_value
					msg.getData().putString("nickname", nickname);
					
					msg.what = 0;
					mHandler.sendMessage(msg);
					
					/** 头像*/
					String path;
					try {
						path = json.getString("figureurl_qq_2");
					    MyImgThread imgThread = new MyImgThread(path);
					    Thread thread = new Thread(imgThread);
					    thread.start();
						
					} catch (JSONException e) {
						e.printStackTrace();
					}
					
				}
				
				@Override
				public void onCancel() {
					
				}
			};
			
			mInfo = new UserInfo(this, mQQAuth.getQQToken());
			mInfo.getUserInfo(iUiListener);
			
		} else {  
            // mUserInfo.setText("");  
            // mUserInfo.setVisibility(android.view.View.GONE);  
            // mUserLogo.setVisibility(android.view.View.GONE);  
        } 
	}

	/**
	 * 开启线程,获取头像
	 */
	class MyImgThread implements Runnable{

		/** 头像地址*/
		private String imgPath;
		
		/** Bitmap*/
		private Bitmap bitmap;
		
		/**
		 * 构造方法
		 */
		public MyImgThread(String imgPath) {
            this.imgPath = imgPath;
		}
		
		@Override
		public void run() {
			bitmap = getImgBitmap(imgPath);
			Message msg = new Message();
			msg.obj = bitmap;
			msg.what = 1;
			mHandler.sendMessage(msg);
		}
		
	}

	
	/**
	 * 根据头像的url 获取bitmap
	 */
	public Bitmap getImgBitmap(String imageUrl){
		
		//显示网络上的图片
		Bitmap bitmap = null;
		HttpURLConnection conn = null;
		InputStream is = null;
		
		try {
			URL myFileUrl = new URL(imageUrl);
			conn = (HttpURLConnection) myFileUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			
			is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
			
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally{
			conn.disconnect();
			try {
				is.close();
				is.reset();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return bitmap;
		
	}
	
}

做完以上步骤就可以实现简单QQ第三方登陆

我说说我自己的简单理解吧,勿喷,谢谢.

我是按照点击之后的流程来说的,

1.先是初始化,控件就不必说了,就是要获取两个实例

// 1.4版本:此处需新增参数,传入应用程序的全局context,可通过activity的getApplicationContext方法获取
		mQQAuth = QQAuth.createInstance(mAppId, this.getApplicationContext());
		//实例化
		mTencent = Tencent.createInstance(mAppId, this);

2.onClickLogin()登陆的方法,先判断当前的会话的有效期

如果有效就调用sdk封装好的接口,需要传入回调的实例,会返回服务器的消息.调用下面的方法

调用login方法后,就会监听登录事件,登录成功或者失败后,会回调监听器里面的几个方法

实现IUiListener接口后,必须要实现接口的三个方法,onComplete  onCancel onError

分别表示第三方登录成功,取消 ,错误。

我们在QQ登录成功后要进行的后续操作就是写在onComplete方法里面的,在这里进行开发即可。

onComplete的参数response封装了一些关键的信息


protected void doComplete(JSONObject values) {} 

QQ登录成功了,我们还想获取一些QQ的基本信息,比如昵称,头像什么的,这个时候怎么办?

sdk给我们提供了一个类UserInfo,这个类中封装了QQ用户的一些信息,我么可以通过这个类拿到这些信息


如何得到这个UserInfo类呢? 

mInfo = new UserInfo(this, mQQAuth.getQQToken());
mInfo.getUserInfo(iUiListener);

得到了userInfo对象后,调用该方法,就得到了用户信息.

获取用户信息成功后,同样会调用onComplete方法,它的第一个参数response就封装了用户的信息,它其实是一个json格式的字符串,在之前的版本中是json格式的,新版本改为了Object。但是我们还是可以把它强转成JSONObject 然后取其中的字段.

如果只需要nickname昵称,以下的代码就可以


JSONObject json = (JSONObject) response;
/** 昵称*/
String nickname = null;
try {
    nickname = ((JSONObject) response).getString("nickname");
} catch (JSONException e) {
    e.printStackTrace();
} 

而要得到头像:

先同理得到头像的路径

/** 头像*/
String path;
try {
    path = json.getString("figureurl_qq_2");					
} catch (JSONException e) {
    e.printStackTrace();
}

然后用getImgBitmap(String url)获取url来得到头像图片

具体方法就不贴了在上面有.

如果晕掉了就无视吧,

注意:

       1.如果你是使用的测试接口的话,那么记得把应用的名字改为: “open_sample”。

       2.在进行登录的时候,可以进行判断是否适合sso登录(但被我注释掉了,)。

以下是运行测试的

1.开始界面                2.登陆                     3.获取资料

       


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值