刚入门做App时,仿照蚂蜂窝App做过第三方登录,但是只做了QQ登陆,但是没有留下系统的学习笔记,只记得按照QQ官网上一步步做下来,现在再做第三方登陆,在这留下学习笔记吧。
–华丽分割线—
根据Bmob官网上说明,微信登陆最麻烦,之前也做过QQ登陆,所以这次先做微博登陆(先去注册微博账号。。。)。
下面开始介绍使用微博第三方登录,
登陆流程图如下图所示:
代码如下:
package com.ppl.get_loc.chat;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
public class ThirdLoginWeibo {
/*
* 微博第三方登录
* */
private String WEIBO_APP_KEY = "你自己的APK_KEY";
private String WEIBO_REDIRECT_URL = "http://www.sina.com";
private String WEIBO_SCOPE =
"email,direct_messages_read,direct_messages_write,"
+ "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
+ "follow_app_official_microblog," + "invitation_write";
private Context mContext;
private Activity mActivity;
public static SsoHandler mSsoHandler;
/** 封装了 "access_token","expires_in","refresh_token",并提供了他们的管理功能 */
private Oauth2AccessToken mAccessToken;
public ThirdLoginWeibo(Context mContext,Activity mActivity) {
super();
this.mContext = mContext;
this.mActivity = mActivity;
}
public void login(){
AuthInfo mAuthInfo = new AuthInfo(mContext, WEIBO_APP_KEY, WEIBO_REDIRECT_URL, WEIBO_SCOPE);
mSsoHandler = new SsoHandler(mActivity, mAuthInfo);
mSsoHandler.authorize(new WeiboAuthListener() {
@Override
public void onWeiboException(WeiboException arg0) {
// TODO Auto-generated method stub
Toast.makeText(mContext,
"Auth exception : " + arg0.getMessage(), Toast.LENGTH_LONG).show();
}
@Override
public void onComplete(Bundle arg0) {
// TODO Auto-generated method stub
//mAccessToken = Oauth2AccessToken.parseAccessToken(values); // 从 Bundle 中解析 Token
mAccessToken = Oauth2AccessToken.parseAccessToken(arg0);
if (mAccessToken.isSessionValid()) {
Toast.makeText(mContext, mAccessToken.getToken(), Toast.LENGTH_LONG).show();
} else {
// 以下几种情况,您会收到 Code:
// 1. 当您未在平台上注册的应用程序的包名与签名时;
// 2. 当您注册的应用程序包名与签名不正确时;
// 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
String code = arg0.getString("code");
String message = "授权失败";
if (!TextUtils.isEmpty(code)) {
message = message + "\nObtained the code: " + code;
}
Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(mContext, "取消授权", Toast.LENGTH_LONG).show();
}
});
}
}
由于没有注意在生成MD5前应在客户端安装需要测试的软件,造成每次登陆会出现下图所示问题,耽误了好长时间,后来重新阅读文档才注意到这一点,重新生成MD5后才能正常用微博登陆,注意点。
至此,完成微博的第三方登陆。