Android集成QQ登录

1.前期准备

1.注册登录腾讯开放平台。
2.创建应用,获取唯一标识APPID,测试学习使用”222222”。
3.下载SDK,解压后导入Jar包并添加依赖。

2.相关配置

1.添加权限(AndroidManifest.xml)

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

2.添加Activity(AndroidManifest.xml)

<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="tencent1105765943" />
         intent-filter>
activity>

<activity
      android:name="com.tencent.connect.common.AssistActivity"
      android:configChanges="orientation|keyboardHidden"
      android:screenOrientation="behind"
      android:theme="@android:style/Theme.Translucent.NoTitleBar" />

3.布局文件(activity_main.xml)


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/tv_nickname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="未登录" />

    <Button
        android:id="@+id/btn_login"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="登录" />

    <Button
        android:id="@+id/btn_logout"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="退出" />

LinearLayout>
3.功能代码
public class MainActivity extends AppCompatActivity {
    //布局文件控件
    private Button login, logout;
    private ImageView img;
    private TextView nickName;
    private String name, imgUrl;

    private static final String APPID = "222222";
    private Tencent mTencent;
    private QQLoginListener mListener;
    private UserInfo userInfo;
    private GetInfoListener mInfoListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        img = (ImageView) findViewById(R.id.iv_img);
        nickName = (TextView) findViewById(R.id.tv_nickname);
        login = (Button) findViewById(R.id.btn_login);
        logout = (Button) findViewById(R.id.btn_logout);
        //初始化Tencent对象
        if (mTencent == null) {
            mTencent = Tencent.createInstance(APPID, this);
        }
        //初始化登陆回调Listener
        if (mListener == null) {
            mListener = new QQLoginListener();
        }
        //登陆按钮点击事件
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QQLogin();
            }
        });
        //退出(登出)按钮点击事件
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QQLogout();
            }
        });
    }

    /**
     * 登录
     */
    private void QQLogin() {
        if (!mTencent.isSessionValid()) {
            mTencent.login(this, "all", mListener);
        }
    }

    /**
     * 退出(登出)
     */
    private void QQLogout() {
        if (mTencent.isSessionValid()) {
            mTencent.logout(this);
            //修改UI
            img.setImageResource(R.mipmap.ic_launcher);
            nickName.setText("未登录");
        }
    }

    /**
     * 登陆结果回调
     */
    private class QQLoginListener implements IUiListener {

        @Override
        public void onComplete(Object o) { //登录成功
            parseResult(o);
            setUserInfo();
        }

        @Override
        public void onError(UiError uiError) { //登录失败

        }

        @Override
        public void onCancel() { //取消登陆

        }
    }


    /**
     * 解析返回的Json串
     */
    private void parseResult(Object o) {
        JSONObject jsonObject = (JSONObject) o;
        try {
            String openID = jsonObject.getString("openid"); //用户标识
            String access_token = jsonObject.getString("access_token"); //登录信息
            String expires = jsonObject.getString("expires_in"); //token有效期
            //配置token
            mTencent.setOpenId(openID);
            mTencent.setAccessToken(access_token, expires);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户信息获取与展示
     */
    private void setUserInfo() {
        QQToken qqToken = mTencent.getQQToken();
        userInfo = new UserInfo(this, qqToken);
        if (mInfoListener == null) {
            mInfoListener = new GetInfoListener();
        }
        userInfo.getUserInfo(mInfoListener);
    }

    /**
     * 获取用户信息回调
     */
    private class GetInfoListener implements IUiListener {

        @Override
        public void onComplete(Object o) { //获取成功,开始展示
            JSONObject jsonObject = (JSONObject) o;
            try {
                name = jsonObject.getString("nickname");
                imgUrl = jsonObject.getString("figureurl_qq_2");  //头像url(100*100像素)
                nickName.setText(name);
                Picasso.with(MainActivity.this).load(imgUrl).into(img);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) { //获取失败

        }

        @Override
        public void onCancel() {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mTencent.onActivityResultData(requestCode, resultCode, data, mListener);
    }
}
4.最后说两句

这里只是写了一个小demo实现了基础的登录与退出功能,更多细节与API请看腾讯的开发指南与API文档

你可能感兴趣的:(Android开发,qq登录)