项目中不泛使用第三方登录 常用的有QQ、新浪微博、微信等
原理基本都是一样的,就是客户端通过按钮去点击 吊起第三方应用AIDL等用第三方账号密码授权 确认授权后返回token/code等唯一标识(证明这个这个第三方账号是你本人)的字符串,把字符串在客户端按type区分,如:手机登录type=0,qq登录type=1,微信登录type=2……
然后把这个唯一标识和type发给服务器去校验 服务器获取第三方账号的个人信息(头像/昵称等)存到数据库,分配应用内唯一的uid,然后返回表明注册成功的json(如
{ret:true,user:{用户信息}}
),客户端解析后确认登录成功,把用户信息存到本地,这样下次客户端再登录的时候就不用去重新登录了。。当然token是有有效期的,主要看服务器怎么去处理,当然一般都不会去处理。。。
下面直接贴代码,主要讲解QQ,新浪微博,微信的客户端操作,因为主要是说明实际操作方法 像友盟,ShareSDK集成好的直接看文档就行,这里说的是没集成过的原生第三方。
首先就是导入jar包,微信是libammsdk.jar/QQ是open_sdk_XXXX.jar/微博是weibosdkcore_xxxx.jar
同时微信需要在项目主包内导入wxapi.WXEntryActivity
首先需要处理清单文件
- <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="'tencent'+在腾讯开发者平台获取的tencentid,如tencent12345678" />
- </intent-filter>
- </activity>
- <activity
- android:name="com.tencent.connect.common.AssistActivity"
- android:configChanges="orientation|keyboardHidden"
- android:screenOrientation="portrait"
- android:theme="@android:style/Theme.Translucent.NoTitleBar" />
-
-
- <activity
- android:name="com.sina.weibo.sdk.component.WeiboSdkBrowser"
- android:configChanges="keyboardHidden|orientation"
- android:exported="false"
- android:windowSoftInputMode="adjustResize" />
- <span style="white-space:pre"> </span><activity
- android:name=".wxapi.WXEntryActivity"
- android:configChanges="keyboardHidden|orientation|screenSize"
- android:exported="true"
- android:screenOrientation="portrait"
- android:theme="@android:style/Theme.Translucent.NoTitleBar" />
然后写两个工具类 Settings和Global ,Settings存储SharePreference对象 用户用户的读取
比如saveUser() getUser() saveCurrentUser() getCurrentUser()这个方法就不多说了 主要看自己的实现
然后是初始化操作 比如首先进入MainActivity 在onCreate里初始化IWXAPI对象 然后调用getCurrentUser() 如果获取为null或者为-1(以uid存储)那么就直接跳转到登录页
如果登录后有操作就startActivityResult或者发广播..
基本原理就是这样
----------------------------
然后建立一个与账号操作相关的基类Activity(为什么与账号相关?因为应用内有可能不只登录会用到这个类 有可能会有账号绑定等页面 这时候就省的去重复写方法了。。)
- public class AuthenticatorActivity extends BaseActivity implements WeiboAuthListener, IUiListener {
- public static final int EXISTED_USER_ERROR = 2005;
-
- private static final String TAG = AuthenticatorActivity.class.getName();
-
- protected static final int VALUE_APP = 1;
-
- protected static final int VALUE_SINA = 2;
-
- protected static final int VALUE_QQ = 3;
-
- protected static final int VALUE_WECHAT = 4;
-
- protected static final String KEY_TOKEN = "token";
-
- protected static final String KEY_OPEN_ID = "openid";
-
- protected static final String KEY_USERNAME = "username";
-
- protected static final String KEY_PASSWORD = "password";
-
- protected static final String KEY_EMAIL = "email";
-
- protected static final int REQUEST_CODE_BIND_OR_REGISTER = 1;
-
- protected static final int REQUEST_CODE_COMPLETE_INFO = 2;
-
- protected AuthInfo mWeiboAuth;
-
- protected Oauth2AccessToken accessToken;
-
- protected SsoHandler mSsoHandler;
-
- protected Tencent mTencent;
-
- private String errorMsg;
-
- BroadcastReceiver mReciver = new BroadcastReceiver() {
- @Override
- public void onReceive (Context context, Intent intent){
- if (intent.getBooleanExtra("result", false)) {
- String code = intent.getStringExtra("code");
- afterLogin(VALUE_WECHAT, code, code);
- } else {
- Toast.makeText(AuthenticatorActivity.this, getString(R.string.log_in_failed), Toast.LENGTH_SHORT).show();
- }
- }
- };
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- initTencent();
- initWeibo();
- initWechat();
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
- lbm.unregisterReceiver(mReciver);
- }
-
- protected void initTencent() {
- try {
- mTencent = Tencent.createInstance(Constants.TencentAppId, getApplicationContext());
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
-
- protected void initWeibo() {
- mWeiboAuth = new AuthInfo(this, Constants.SinaAppKey, Constants.SinaAppRedirectURI,
- Constants.SinaScope);
- mSsoHandler = new SsoHandler(this, mWeiboAuth);
- }
-
- protected void initWechat() {
- LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
- lbm.registerReceiver(mReciver, new IntentFilter(Constants.ACTION_WECHAT_LOGIN));
- }
-
-
- @Override
- public void onComplete(Object o) {
- JSONObject object = (JSONObject) o;
- try {
- LogUtils.d(TAG, "onTencentComplete, object is " + object.toString());
- String token = object.optString("access_token");
- String openId = object.optString("openid");
- String expireTime = object.optString("expires_in");
- Oauth2AccessToken qqAccessToken = new Oauth2AccessToken(token, expireTime);
- if (qqAccessToken.isSessionValid()) {
- String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new java.util.Date
- (qqAccessToken
- .getExpiresTime()));
- LogUtils.d(TAG, "QQ log in, expire date is " + date);
- }
- afterLogin(VALUE_QQ, openId, token);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public void onError(UiError uiError) {
- LogUtils.d(TAG,
- "onError, uiError is " + uiError.errorDetail + ", " + uiError.errorMessage);
- Toast.makeText(this,
- TextUtils.isEmpty(uiError.errorMessage) ? getString(R.string.qq_log_in_failed)
- : uiError.errorMessage, Toast.LENGTH_SHORT).show();
- }
-
- @Override
- public void onComplete(Bundle bundle) {
- try {
- accessToken = Oauth2AccessToken.parseAccessToken(bundle);
- LogUtils.d(TAG,
- "onComplete, accessToken is " + accessToken.getUid() + ":" + accessToken
- .getToken() + ", expireTime is " + accessToken.getExpiresTime());
- if (accessToken.isSessionValid()) {
- String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
- .format(new java.util.Date(accessToken.getExpiresTime()));
- LogUtils.d(TAG, "weibo log in, expire date is " + date);
- afterLogin(VALUE_SINA, accessToken.getUid(), accessToken.getToken());
- }
- } catch (Exception e) {
- e.printStackTrace();
- Toast.makeText(this, getString(R.string.log_in_failed), Toast.LENGTH_SHORT).show();
- }
- }
-
- @Override
- public void onWeiboException(WeiboException e) {
- LogUtils.d(TAG, "e.message is " + e.getLocalizedMessage());
- e.printStackTrace();
- Toast.makeText(this, String.format(getString(R.string.weibo_error), e.getMessage()),
- Toast.LENGTH_LONG).show();
-
- }
-
- @Override
- public void onCancel() {
-
- }
-
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if ((requestCode == REQUEST_CODE_BIND_OR_REGISTER
- || requestCode == REQUEST_CODE_COMPLETE_INFO) && resultCode == RESULT_OK) {
- setResult(RESULT_OK);
- finish();
- return;
- }
-
- try {
- if (mSsoHandler != null) {
- mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- protected void afterLogin(int type, String uid, String token) {
-
- }
-
-
- protected void saveUserInfo(LogInResponse result) {
- Settings.saveUser(result.data);
- Global.currentUser = result.data;
- }
- }
然后就是子类的实现了 ,登录页的登录事件代码
- <span style="white-space:pre"> </span>case R.id.weibo_log_in_button:
- mSsoHandler.authorize(this);
- break;
- case R.id.qq_log_in_button:
- if (mTencent == null) {
- Utils.showToast(R.string.qq_not_installed);
- return;
- }
- mTencent.login(this, "get_user_info", this);
- break;
- case R.id.weixin_log_in_button:
-
- if (Global.mWxApi.isWXAppInstalled() && Global.mWxApi.isWXAppSupportAPI()) {
- final SendAuth.Req req = new SendAuth.Req();
- req.scope = "snsapi_userinfo";
- req.state = "none";
- Global.mWxApi.sendReq(req);
- } else {
- Utils.showToast(R.string.weixin_oauth_failed);
- }
- break;
也就是说 当我们点击之后 如果授权成功 最终会调用afterLogin方法,里面有三个参数 type uid token,当然 直接登录成功也可以调用这个方法 uid = username,token=password..
然后在这个方法里向我们自己的服务器发请求就可以 服务器返回成功地指示后我们再调用子类重写的saveUserInfo()
- @Override
- protected void saveUserInfo(LogInResponse result) {
-
- super.saveUserInfo(result);
-
- Settings.setCurrentUid(result.data.uid);
- }
这样就基本实现第三方登录了
接下来是微信的WXEntryActivity 因为我们使用的是LocalBroadCastRecevier,因此我们在微信登录成功后需要发送广播给实现基类的登录页Activity
- public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- Global.mWxApi.handleIntent(getIntent(), this);
- }
-
- @Override
- protected void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- Global.mWxApi.handleIntent(intent, this);
- }
-
-
- @Override
- public void onReq(BaseReq baseReq) {
-
- }
-
- @Override
- public void onResp(BaseResp baseResp) {
- if (baseResp instanceof SendAuth.Resp) {
-
- LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
- Intent intent = new Intent(Constants.ACTION_WECHAT_LOGIN);
- intent.putExtra("result", baseResp.errCode == BaseResp.ErrCode.ERR_OK);
- intent.putExtra("code", ((SendAuth.Resp) baseResp).code);
- lbm.sendBroadcast(intent);
- finish();
- }else {
- int result = 0;
- switch (baseResp.errCode) {
- case BaseResp.ErrCode.ERR_OK:
- result = R.string.errcode_success;
- break;
- case BaseResp.ErrCode.ERR_USER_CANCEL:
- result = R.string.errcode_cancel;
- break;
- case BaseResp.ErrCode.ERR_AUTH_DENIED:
- result = R.string.errcode_deny;
- break;
- default:
- result = R.string.errcode_unknown;
- break;
- }
-
- Toast.makeText(this, getString(result), Toast.LENGTH_LONG).show();
- finish();
- }
- }
- }
这样就基本完成登录和登录后避免再次登录了,接下来还有一些问题,
1.微信登录需要将apk打包签名 并通过微信的一个校验apk在里面输入包名 生成一个校验码粘贴到开发者平台才能够使用 而且费用300一年
2.微博也需要校验包名
3.每次重复签名很麻烦 又懒得换成测试版的签名 如果使用as或者idea的话 可以在build.gradle里输入
4.微信登录在开发者平台弄好之后不是马上就能用 有1个小时左右的延迟
- signingConfigs {
- myConfig {
- storeFile file("你的keystore文件,相对路径")
- storePassword 库密码
- keyAlias alias
- keyPassword 密码
- }
- }
-
- buildTypes {
- //是否混淆
- minifyEnabled true
- //混淆规则
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- //调用上面的签名方法
- signingConfig signingConfigs.myConfig
- }
- //调用上面的签名方法
- signingConfig signingConfigs.myConfig
- }
- }