天天看點

android qq第三方登入(騰訊sdk)

一般的項目中都會用到第三方登入,常見的有qq,微信,微網誌,這裡給大家實作qq第三方登入的方法。第三方登陸的方法有很多,有內建友盟的,有內建mob的,還有使用騰訊官方sdk的,個人認為官方的最友善一點,當然别人內建的也有好處,畢竟别人也寫了好多代碼,但就是怕他們寫的那些代碼有備援。貼代碼:

先要去騰訊官方open.qq.com官方網址下載下傳sdk:http://wiki.open.qq.com/wiki/mobile/SDK%E4%B8%8B%E8%BD%BD我的是現在了最新最上變的那個,然後解壓把jar檔案夾的那個jar檔案直接拷到libs檔案夾下。

1,配置AndroidManifest:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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你的AppId" />
            </intent-filter>
        </activity>
        <!-- qqSDK_V2.0引入了AssistActivity -->
        <activity
            android:name="com.tencent.connect.common.AssistActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />           

fragment_login.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white" >

    <include
        android:id="@+id/login_title"
        layout="@layout/include_title" />

    <LinearLayout
        android:id="@+id/login_linear_user"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/login_title"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:orientation="vertical" >
        <EditText
            android:id="@+id/login_user_edt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:drawableLeft="@drawable/ic_launcher"
            android:hint="請輸入使用者名:" />
        <EditText
            android:id="@+id/login_pwd_edt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:drawableLeft="@drawable/ic_launcher"
            android:hint="請輸入密碼:" />
    </LinearLayout>


    <TextView
        android:id="@+id/login_forget_pwd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/login_linear_user"
        android:text="忘記密碼" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_below="@+id/login_forget_pwd"
        android:layout_marginTop="5dp"
        android:orientation="vertical" >

        <Button
            android:id="@+id/login_btn"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:text="登入" />

        <Button
            android:id="@+id/login_register_btn"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:text="注冊" />
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/login_third_party"
        android:layout_centerHorizontal="true"
        android:text="—————第三方快速登入——————" />

    <LinearLayout
        android:id="@+id/login_third_party"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="50dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/login_qq"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_marginRight="6dp"
            android:background="@drawable/third_party_qq" />

        <ImageButton
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_marginLeft="6dp"
            android:layout_marginRight="6dp"
            android:background="@drawable/third_party_wx" />

        <ImageButton
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_marginLeft="6dp"
            android:background="@drawable/third_party_xl" />
    </LinearLayout>

</RelativeLayout>           

LoginFragment.java:

package com.example.demo.fragment;

import org.json.JSONObject;

import com.example.sihaiproject.R;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Toast;

public class LoginFragment extends Fragment {
    private View view;
    @ViewInject(R.id.login_qq)
    private ImageButton loginQq;
    private Tencent mTencent;
    private String APP_ID = "1105225312";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = View.inflate(getActivity(), R.layout.fragment_login, null);
        ViewUtils.inject(this, view);

        return view;
    }

    @OnClick(R.id.login_qq)
    public void loginQq(View view) {
        mTencent = Tencent.createInstance(APP_ID, getActivity());
        if (!mTencent.isSessionValid())
        {
            mTencent.login(this, "all", loginListener);
            getUserInfo();
        }
    }

    IUiListener loginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values) {

            System.out.println("loginListener" + values.toString());
            /**
             * 擷取用使用者資訊前必須調用。
             */
            initOpenidAndToken(values);
            // 擷取使用者資訊
            getUserInfo();

        }
    };

    /**
     * 擷取使用者資訊
     */
    public void getUserInfo() {
        if (mTencent != null && mTencent.isSessionValid()) {

            IUiListener listener = new BaseUiListener() {
                @Override
                protected void doComplete(JSONObject values) {

                    System.out.println("updateUserInfo------" + values);

                }

            };

            /**
             * UserInfo:QQ提供的使用者資訊類
             */
            UserInfo userInfo = new UserInfo(getActivity(), mTencent.getQQToken());
            userInfo.getUserInfo(listener);

        }
    }

    /***
     * 初始化openid
     * 
     * @param jsonObject
     */
    public void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires) && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        mTencent.onActivityResultData(requestCode, resultCode, data, loginListener);
    }
    private class BaseUiListener implements IUiListener {

        /**
         * 取消授權
         */
        @Override
        public void onCancel() {
        }

        /**
         * 授權成功
         */
        @Override
        public void onComplete(Object response) {
            JSONObject jsonResponse = (JSONObject) response;

            Toast.makeText(getActivity(), jsonResponse.toString(), 1).show();

            doComplete(jsonResponse);
        }

        /**
         * 授權失敗
         */
        @Override
        public void onError(UiError arg0) {

        }

        protected void doComplete(JSONObject values) {

        }
    }

}
           

其實也是看官方文檔做的,最詳細的還是去騰訊開發平台去看詳細文檔,我這裡隻不過更清楚的看到一個登陸功能。這些代碼運作後可以擷取到qq号,qq名稱,qq頭像……..

如果報錯:java.lang.SecurityException: ConnectivityService不用查了,是你配置檔案裡的

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

沒寫或寫錯了。

tencent你的AppId要去開發者平台首頁→移動應用→建立應用→擷取appId。

java代碼我用的是xutils2.x和fastjson,如果直接複制代碼會報錯的,根據自己的需要提取代碼。