1. 程式人生 > >第三方QQ登入和分享

第三方QQ登入和分享

目前大多數APP都包含了第三方平臺的登入,特別是QQ和微信,這篇部落格主要講的是如何實現QQ第三方平臺實現QQ登入和分享功能,功能包含:

  • 登入授權登入獲取使用者資訊(暱稱,頭像,地址等)
  • QQ分享給好友
  • QQ分享到空間

先看看效果圖:

 

要實現以上功能,首先得去騰訊開放平臺 註冊成為開發者,然後建立應用,得到 APPID,如下圖:

名稱就是APP名稱,可上傳Logo圖片,授權登入時會顯示授權給那個APP,效果如圖:

建立成功後,取得APP ID即可,完成以上功能了。

新增這兩個jar包

開啟我們的Androidmanifest 在裡面加入許可權和註冊Activity 如下

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.shiran.qqlogindemo"> <!-- QQ登入授權所需許可權 --> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application
android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme">
<activity android:name=".MainActivity"> <intent-filter> <action
android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- 註冊SDKActivity --> <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="tencent1105602574" /> <!-- 開放平臺獲取的APPID --> </intent-filter> </activity> <activity android:name="com.tencent.connect.common.AssistActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:screenOrientation="portrait"/> </application> </manifest>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

佈局檔案activity_main 就一個Button按鈕

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.shiran.qqlogindemo.MainActivity">

  <Button
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="點選QQ登入"
      android:onClick="buttonLogin"
      android:layout_centerInParent="true"
      android:textSize="16sp"
      android:textColor="#f4736e"/>
</RelativeLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

下面就是我們的MainActivity中的程式碼了

package com.shiran.qqlogindemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final String APP_ID = "1105602574";//官方獲取的APPID
    private Tencent mTencent;
    private BaseUiListener mIUiListener;
    private UserInfo mUserInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //傳入引數APPID和全域性Context上下文
        mTencent = Tencent.createInstance(APP_ID,MainActivity.this.getApplicationContext());
    }

    public void buttonLogin(View v){
        /**通過這句程式碼,SDK實現了QQ的登入,這個方法有三個引數,第一個引數是context上下文,第二個引數SCOPO 是一個String型別的字串,表示一些許可權
         官方文件中的說明:應用需要獲得哪些API的許可權,由“,”分隔。例如:SCOPE = “get_user_info,add_t”;所有許可權用“all”
         第三個引數,是一個事件監聽器,IUiListener介面的例項,這裡用的是該介面的實現類 */
        mIUiListener = new BaseUiListener();
        //all表示獲取所有許可權
        mTencent.login(MainActivity.this,"all", mIUiListener);
    }

    /**
     * 自定義監聽器實現IUiListener介面後,需要實現的3個方法
     * onComplete完成 onError錯誤 onCancel取消
     */
    private class BaseUiListener implements IUiListener{

        @Override
        public void onComplete(Object response) {
            Toast.makeText(MainActivity.this, "授權成功", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "response:" + response);
            JSONObject obj = (JSONObject) response;
            try {
                String openID = obj.getString("openid");
                String accessToken = obj.getString("access_token");
                String expires = obj.getString("expires_in");
                mTencent.setOpenId(openID);
                mTencent.setAccessToken(accessToken,expires);
                QQToken qqToken = mTencent.getQQToken();
                mUserInfo = new UserInfo(getApplicationContext(),qqToken);
                mUserInfo.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object response) {
                        Log.e(TAG,"登入成功"+response.toString());//獲得登入使用者
JSONObjectjson  = (JSONObject) response;
try {
String figureurl_qq_1 = json.getString("figureurl_qq_1");
// ImageLoader.getInstance().displayImage(figureurl_qq_1,image);
} catch (JSONException e) {
e.printStackTrace();
}
} @Override public void onError(UiError uiError) { Log.e(TAG,"登入失敗"+uiError.toString()); } @Override public void onCancel() { Log.e(TAG,"登入取消"); } });catch (JSONException e) { e.printStackTrace(); } } @Override public void onError(UiError uiError) { Toast.makeText(MainActivity.this, "授權失敗", Toast.LENGTH_SHORT).show(); } @Override public void onCancel() { Toast.makeText(MainActivity.this, "授權取消", Toast.LENGTH_SHORT).show(); } } /** * 在呼叫Login的Activity或者Fragment中重寫onActivityResult方法 * @param requestCode * @param resultCode * @param data */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == Constants.REQUEST_LOGIN){ Tencent.onActivityResultData(requestCode,resultCode,data,mIUiListener); } super.onActivityResult(requestCode, resultCode, data); }}
複製程式碼
    //qq分享
    private void onClickShare() {
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
                QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, "要分享的標題");
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "要分享的摘要");
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,
                "http://blog.csdn.net/DickyQie/article/list/1");
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,
                "http://imgcache.qq.com/qzone/space_item/pre/0/66768.gif");
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "切切歆語");
        params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "其他附加功能");
        mTencent.shareToQQ(MainActivity.this, params, new shareListener());
    }
複製程式碼 複製程式碼
  private void shareToQQzone() {
        try {
            final Bundle params = new Bundle();
            params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,
                    QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, "切切歆語");
            params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, "sss");
            params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,
                    "http://blog.csdn.net/DickyQie/article/list/1");
            ArrayList<String> imageUrls = new ArrayList<String>();
            imageUrls.add("http://media-cdn.tripadvisor.com/media/photo-s/01/3e/05/40/the-sandbar-that-links.jpg");
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
            params.putInt(QzoneShare.SHARE_TO_QQ_EXT_INT,
                    QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
            Tencent mTencent = Tencent.createInstance("申請的APPID",
                    MainActivity.this);
            mTencent.shareToQzone(MainActivity.this, params,
                    new shareListener());
        } catch (Exception e) {
        }
    }
複製程式碼