Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 接入 QQ 第三方登入:從 OpenID 到頭像顯示的完整實作

編輯:關於 Android 程式設計

專案裡要接 QQ 第三方登入,折騰一輪總算跑通了,把過程記錄下來,一方面免得自己日後遺忘,另一方面也希望能幫到同路人。

準備工作

第一步是到騰訊官方的開放平台下載 SDK 與 DEMO:https://wiki.open.qq.com/wiki/mobile/SDK下載 。本文整理的是一個精簡後的 DEMO。

先搞懂原理

「用 QQ 登入我們的應用」這句話容易誤導人以為不用註冊,實際上帳號還是要在後台建立的,只是使用者不察覺。而建立帳號必須有一個唯一標識,也就是畫面上那串字母數字組合——OpenID。

拿到 OpenID 之後,就能把它當成使用者在我方系統中的唯一鍵,後續再依需求向騰訊索取暱稱、頭像等資料。

其中 AppConstant 用來集中放置 APP_ID。之所以獨立成一個類,是因為日後很可能還會接入微信、微博等其他第三方登入,集中管理比較清爽。Util 則是依 URL 從網路抓圖片的工具類。

AndroidManifest.xml 的兩處關鍵設定

第一處是 intent-filter,缺少它 SDK 無法在登入完成後跳回你的應用:

<intent-filter>
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="tencent222222" /><!-- 這裡要換成你的 APP_ID -->
</intent-filter>

scheme 必須是 "tencent" 加上你的 APP_ID,一個字都不能差,這是 SDK 回跳的依據。

第二處是權限:

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

布局檔

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/login"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="登錄" />

    <ImageView
        android:id="@+id/user_logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/user_nickname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#80505050"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/user_openid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity 實作

public class MainActivity extends Activity implements OnClickListener {
    TextView openidTextView;
    TextView nicknameTextView;
    Button loginButton;
    ImageView userlogo;

    private Tencent mTencent;
    public static QQAuth mQQAuth;
    public static String mAppid;
    public static String openidString;
    public static String nicknameString;
    public static String TAG = "MainActivity";
    Bitmap bitmap = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        loginButton = (Button) findViewById(R.id.login);
        loginButton.setOnClickListener(this);
        openidTextView = (TextView) findViewById(R.id.user_openid);
        nicknameTextView = (TextView) findViewById(R.id.user_nickname);
        userlogo = (ImageView) findViewById(R.id.user_logo);
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                LoginQQ();
                break;
            default:
                break;
        }
    }

    // 呼叫 QQ 登入的關鍵程式碼
    public void LoginQQ() {
        // APP_ID 請換成你申請的 AppID,這裡用的是官方 DEMO 的測試 ID
        mAppid = AppConstant.APP_ID;
        // 第一個參數是 APP_ID,第二個是全域 Context,這行完成 SDK 初始化
        mTencent = Tencent.createInstance(mAppid, getApplicationContext());

        /**
         * SDK 靠這個方法完成 QQ 登入,共三個參數:
         * 1. context 上下文
         * 2. scope 字串,表示需要哪些 API 權限,多個以逗號分隔,例如
         *    "get_user_info,add_t";全部權限則填 "all"
         * 3. IUiListener 介面的實例,用來接收登入結果
         */
        mTencent.login(MainActivity.this, "all", new BaseUiListener());
    }

    /**
     * 自訂監聽器實作 IUiListener 後,必須實作三個方法:
     * onComplete 登入成功、onCancel 使用者取消、onError 發生錯誤
     */
    private class BaseUiListener implements IUiListener {
        public void onCancel() {
        }

        public void onComplete(Object response) {
            Toast.makeText(getApplicationContext(), "登錄成功", 0).show();
            try {
                // 回傳的是 JSON 格式,取出需要的欄位
                // 不確定能拿到什麼,就先把整個 response 印出來看
                Log.e(TAG, "-------------" + response.toString());
                openidString = ((JSONObject) response).getString("openid");
                openidTextView.setText(openidString);
                Log.e(TAG, "-------------" + openidString);
                // access_token = ((JSONObject) response).getString("access_token");
                // expires_in = ((JSONObject) response).getString("expires_in");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            /**
             * 到此 OpenID 已到手,登入可謂成功。但通常還需要暱稱、頭像等資料。
             * SDK 提供了 UserInfo 類,其中封裝了 QQ 使用者的基本資訊。
             * 取得方式:先用 mTencent.getQQToken() 拿到 token,再據此建立 UserInfo。
             */
            QQToken qqToken = mTencent.getQQToken();
            UserInfo info = new UserInfo(getApplicationContext(), qqToken);

            info.getUserInfo(new IUiListener() {
                public void onComplete(final Object response) {
                    Log.e(TAG, "---------------111111");
                    Message msg = new Message();
                    msg.obj = response;
                    msg.what = 0;
                    mHandler.sendMessage(msg);

                    /**
                     * 頭像需要另外下載,所以開了一條執行緒;
                     * 若只要文字資訊,直接在 mHandler 中處理即可
                     */
                    new Thread() {
                        @Override
                        public void run() {
                            JSONObject json = (JSONObject) response;
                            try {
                                bitmap = Util.getbitmap(json.getString("figureurl_qq_2"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            Message msg = new Message();
                            msg.obj = bitmap;
                            msg.what = 1;
                            mHandler.sendMessage(msg);
                        }
                    }.start();
                }

                public void onCancel() {
                    Log.e(TAG, "--------------111112");
                }

                public void onError(UiError arg0) {
                    Log.e(TAG, "-111113" + ":" + arg0);
                }
            });
        }

        public void onError(UiError arg0) {
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                JSONObject response = (JSONObject) msg.obj;
                if (response.has("nickname")) {
                    try {
                        nicknameString = response.getString("nickname");
                        nicknameTextView.setText(nicknameString);
                        Log.e(TAG, "--" + nicknameString);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } else if (msg.what == 1) {
                Bitmap bitmap = (Bitmap) msg.obj;
                userlogo.setImageBitmap(bitmap);
            }
        }
    };
}

上圖是登入 QQ 後的回傳 LOG。

上圖則是呼叫 UserInfo 之後取得的 LOG。

兩個輔助類

public class AppConstant {
    public static String APP_ID = "222222";
}
public class Util {
    public static String TAG = "UTIL";

    public static Bitmap getbitmap(String imageUri) {
        Log.v(TAG, "getbitmap:" + imageUri);
        // 顯示網路上的圖片
        Bitmap bitmap = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        try {
            URL myFileUrl = new URL(imageUri);
            conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            Log.v(TAG, "image download finished." + imageUri);
        } catch (IOException e) {
            e.printStackTrace();
            Log.v(TAG, "getbitmap bmp fail---");
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return bitmap;
    }
}

到這裡,OpenID 這個關鍵的唯一標識已經拿到,接著只要看你的後端登入介面還需要哪些欄位,補齊就能完成整條登入流程。

幾個實作上的建議

上述程式碼為了聚焦主流程,把一些工程上的細節簡化了,實際上線時建議補強。

第一,網路請求不能放在主執行緒。Android 4.0 之後 NetworkOnMainThreadException 會直接讓程式崩潰,登入與抓圖都應該移到非同步任務或執行緒中。

第二,务必呼叫 mTencent.releaseSSOAppAsyncShowFragment()(若使用含 SSO 界面的版本)並在 Activity 的 onActivityResult 中把結果轉交給 mTencent,否則某些授權路徑會收不到回呼。

第三,access_token 有時效。它與 expires_in 是成對出現的,實務上要保存下來並在過期前刷新,而不是每次登入都重新走一遍授權。

第四,OpenID 只在同一個 APP_ID 下唯一。也就是說同一個 QQ 帳號在你的應用與另一個開發者的應用中會得到不同的 OpenID,這點在設計資料表主鍵時要想清楚。

最後,不要把 APPSecret 放進用戶端。任何需要 AppKey/AppSecret 的伺服器端 API 呼叫,都應該由你的後端代理執行。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved