首先在新浪微博和腾讯的开发平台下载相应的SDK,这里不作介绍,直接上代码:
LoginActivity.java
package com.qingning.share;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import com.qingning.share.util.Constant;
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;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class LoginActivity extends Activity {
private Context mContext;
private Window mWindow;
/** 新浪微博登陆相关 **/
private AuthInfo mAuthInfo;
/** 注意:SsoHandler 仅当 SDK 支持 SSO 时有效 */
private SsoHandler mSsoHandler;
private AuthListener mAuthListener;
/** 封装了 "access_token","expires_in","refresh_token",并提供了他们的管理功能 */
private Oauth2AccessToken mAccessToken;
/** QQ登陆相关 **/
private Tencent mTencent;
private BaseUiListener mBaseUiListener;
private QQToken mQQToken;
private UserInfo mUserInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setFinishOnTouchOutside(false); //点击区域外不消失
setContentView(getResources().getIdentifier("dialog_login", "layout", getPackageName()));
//进入的动画
mWindow = getWindow();
mWindow.setGravity(Gravity.CENTER);
mWindow.setWindowAnimations(getResources().getIdentifier("dialog", "style", getPackageName()));
final ImageButton btnClose = (ImageButton) findViewById(getResources().getIdentifier("dialog_close", "id", getPackageName()));
final ImageButton btnWeixin = (ImageButton) findViewById(getResources().getIdentifier("weixin_login", "id", getPackageName()));
final ImageButton btnWeibo = (ImageButton) findViewById(getResources().getIdentifier("weibo_login", "id", getPackageName()));
final ImageButton btnQQ = (ImageButton) findViewById(getResources().getIdentifier("qq_login", "id", getPackageName()));
final Button btnPhone = (Button) findViewById(getResources().getIdentifier("phone_login", "id", getPackageName()));
mContext = this;
OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View view) {
if (view == btnClose) {
finish();
//退出的动画
finishAnimation();
} else if (view == btnWeixin) {
} else if (view == btnWeibo) {
if (!isAppInstalled(Constant.SINA_PACKAGE_NAME)) {
Toast.makeText(mContext, String.format(getString(getResources().getIdentifier("please_install_first", "string", getPackageName())), getString(getResources().getIdentifier("dialog_weibo_login", "string", getPackageName()))), Toast.LENGTH_LONG).show();
return;
}
//创建微博实例
mAuthInfo = new AuthInfo(mContext, Constant.SINA_APP_KEY, Constant.SINA_REDIRECT_URL, Constant.SINA_SCOPE);
mSsoHandler = new SsoHandler(LoginActivity.this, mAuthInfo);
mAuthListener = new AuthListener();
mSsoHandler.authorizeClientSso(mAuthListener);
} else if (view == btnQQ) {
if (!isAppInstalled(Constant.TENCENT_PACKAGE_NAME)) {
Toast.makeText(mContext, String.format(getString(getResources().getIdentifier("please_install_first", "string", getPackageName())), getString(getResources().getIdentifier("dialog_qq_login", "string", getPackageName()))), Toast.LENGTH_LONG).show();
return;
}
//初始化腾讯对象
mTencent = Tencent.createInstance(Constant.TENCENT_APP_ID, mContext);
mBaseUiListener = new BaseUiListener();
mTencent.login(LoginActivity.this, Constant.TENCENT_SCOPE, mBaseUiListener);
} else if (view == btnPhone) {
finish();
//退出的动画
finishAnimation();
}
}
};
btnClose.setOnClickListener(onClickListener);
btnWeixin.setOnClickListener(onClickListener);
btnWeibo.setOnClickListener(onClickListener);
btnQQ.setOnClickListener(onClickListener);
btnPhone.setOnClickListener(onClickListener);
}
@Override
protected void onPause() {
mWindow.setWindowAnimations(-1);
super.onPause();
}
//退出的动画
private void finishAnimation() {
overridePendingTransition(getResources().getIdentifier("dialog_enter", "anim", getPackageName()), getResources().getIdentifier("dialog_exit", "anim", getPackageName()));
}
//拦截返回键,实现自定义的退出动画
@Override
public void onBackPressed() {
finish();
finishAnimation();
}
/**
* 微博认证授权回调类。
* 1. SSO 授权时,需要在 {@link #onActivityResult} 中调用 {@link SsoHandler#authorizeCallBack} 后,
* 该回调才会被执行。
* 2. 非 SSO 授权时,当授权结束后,该回调就会被执行。
* 当授权成功后,请保存该 access_token、expires_in、uid 等信息到 SharedPreferences 中。
*/
private class AuthListener implements WeiboAuthListener {
@Override
public void onComplete(Bundle values) {
//从 Bundle 中解析 Token
mAccessToken = Oauth2AccessToken.parseAccessToken(values);
if (mAccessToken != null && mAccessToken.isSessionValid()) {
Toast.makeText(mContext, getString(getResources().getIdentifier("authorize_success", "string", getPackageName())), Toast.LENGTH_SHORT).show();
String nickname = values.getString("com.sina.weibo.intent.extra.NICK_NAME");
String access_token = values.getString("access_token");
String uid = values.getString("uid");
//GET请求获取用户的信息
try {
URL url = new URL("https://api.weibo.com/2/users/show.json?access_token=" + access_token + "&uid=" + uid);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
int code = conn.getResponseCode();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
if (code == 200) {
InputStream is = conn.getInputStream();
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
}
String jsonString = new String(baos.toByteArray());
JSONObject jsonObject = new JSONObject(jsonString);
String icon = jsonObject.getString("profile_image_url");
Intent intent = new Intent();
intent.putExtra("nickname", nickname);
intent.putExtra("icon", icon);
setResult(Constant.LOGIN_RESULT_OK, intent);
finish();
finishAnimation();
} catch (Exception e) {
Log.d("chengcj1", e.getMessage());
}
} else {
// 以下几种情况,您会收到 Code:
// 1. 当您未在平台上注册的应用程序的包名与签名时;
// 2. 当您注册的应用程序包名与签名不正确时;
// 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
String code = values.getString("code");
String message = getString(getResources().getIdentifier("authorize_fail", "string", getPackageName()));
if (!TextUtils.isEmpty(code)) {
message = message + "\n Obtained the code: " + code;
}
Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancel() {
Toast.makeText(mContext, getString(getResources().getIdentifier("authorize_cancel", "string", getPackageName())), Toast.LENGTH_LONG).show();
}
@Override
public void onWeiboException(WeiboException e) {
Toast.makeText(mContext, "WeiboException : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private class BaseUiListener implements IUiListener {
@Override
public void onError(UiError e) {
Toast.makeText(mContext, getString(getResources().getIdentifier("login_fail", "string", getPackageName())) + e.errorMessage, Toast.LENGTH_LONG).show();
}
@Override
public void onComplete(Object response) {
// 获得的数据是JSON格式的,获得你想获得的内容
JSONObject responseJsonObject = (JSONObject) response;
int ret = responseJsonObject.optInt("ret");
if (ret == 0) { //登陆成功
Toast.makeText(mContext, getString(getResources().getIdentifier("login_success", "string", getPackageName())), Toast.LENGTH_LONG).show();
// 用于唯一标识用户身份(每一个openid与QQ号码对应)
String openID = responseJsonObject.optString("openid");
//用户进行应用邀请、分享、支付等基本业务请求的凭据
final String accessToken = responseJsonObject.optString("access_token");
//access_token的有效时间,在有效期内可以发起业务请求,过期失效
String expires = responseJsonObject.optString("expires_in");
mTencent.setOpenId(openID);
mTencent.setAccessToken(accessToken, expires);
//QQ登陆成功,获取用户的信息,如我们还想获取一些QQ的基本信息,比如昵称,头像什么的
mQQToken = mTencent.getQQToken();
mUserInfo = new UserInfo(mContext, mQQToken);
mUserInfo.getUserInfo(new IUiListener() {
@Override
public void onError(UiError e) {
}
@Override
public void onComplete(Object response) {
JSONObject responseJsonObject = (JSONObject) response;
//获取昵称
String nickname = responseJsonObject.optString("nickname");
//获取用户头像
String icon = responseJsonObject.optString("figureurl_qq_2");
Intent intent = new Intent();
intent.putExtra("nickname", nickname);
intent.putExtra("logo", icon);
setResult(Constant.LOGIN_RESULT_OK, intent);
finish();
finishAnimation();
}
@Override
public void onCancel() {
}
});
}
}
@Override
public void onCancel() {
Toast.makeText(mContext, getString(getResources().getIdentifier("login_cancel", "string", getPackageName())), Toast.LENGTH_LONG).show();
}
}
/**
* 应用调用Android_SDK接口时,如果要成功接收到回调,需要再调用接口的Activity的onActivityResult方法中增加如下代码
* http://wiki.open.qq.com/wiki/mobile/SDK下载
* http://open.weibo.com/wiki/SDK
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Tencent.onActivityResultData(requestCode, resultCode, data, mBaseUiListener);
// SSO 授权回调
// 重要:发起 SSO 登陆的 Activity 必须重写 onActivityResult
if (mSsoHandler != null) {
mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
}
}
/**
* 检测手机上是否安装相应的平台
* @param packageName 包名
* @return
*/
private boolean isAppInstalled(String packageName) {
try {
getPackageManager().getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
return true;
} catch (Exception e) {
return false;
}
}
}