Android實現QQ第三方登陸

先看下效果圖吧 java

\\\\\

原理:咱們要使用QQ登陸咱們的應用,不是不用註冊,是咱們在後臺爲用戶註冊了,可是用戶不知道,註冊須要惟一標識,上圖的那串字母與數字的組合就是咱們要得到的惟一標識:OpenID。 android

\

其中,AppConstant中是用來放置APPID的,因爲考慮到還可能引入其餘第三方登陸,爲方便管理,故建立此類。Util是根據路徑從網上獲取圖片的處理類。 json

首先在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="tencent1104613941" />
            </intent-filter>
        </activity> ide

而後是兩個權限: 佈局

<uses-permission android:name="android.permission.INTERNET">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">
接下來是佈局文件,activity_main.xml登陸按鈕,獲取頭像、暱稱、openid的textview:

<linearlayout xmlns:android=" http://schemas.android.com/apk/res/android"xmlns:tools=" http://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">
    
 
</textview></textview></imageview></button></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);
        //用來登陸的Button
        loginButton=(Button)findViewById(R.id.login);
        loginButton.setOnClickListener(this);
        //用來顯示OpenID的textView
        openidTextView=(TextView)findViewById(R.id.user_openid);
        //用來顯示暱稱的textview
        nicknameTextView=(TextView)findViewById(R.id.user_nickname);
       //用來顯示頭像的Imageview
        userlogo=(ImageView)findViewById(R.id.user_logo);
         
    }
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.login:
            LoginQQ();
            break;
 
        default:
            break;
        }
    }
    //這裏是調用QQ登陸的關鍵代碼
    public void LoginQQ() {
        //這裏的APP_ID請換成你應用申請的APP_ID,我這裏使用的是DEMO中官方提供的測試APP_ID 222222
        mAppid = AppConstant.APP_ID;
        //第一個參數就是上面所說的申請的APPID,第二個是全局的Context上下文,這句話實現了調用QQ登陸
        mTencent = Tencent.createInstance(mAppid,getApplicationContext());
        /**經過這句代碼,SDK實現了QQ的登陸,這個方法有三個參數,第一個參數是context上下文,第二個參數SCOPO 是一個String類型的字符串,表示一些權限 
        官方文檔中的說明:應用須要得到哪些API的權限,由「,」分隔。例如:SCOPE = 「get_user_info,add_t」;全部權限用「all」  
        第三個參數,是一個事件監聽器,IUiListener接口的實例,這裏用的是該接口的實現類 */
        mTencent.login(MainActivity.this,"all", new BaseUiListener());
             
    }
    /**當自定義的監聽器實現IUiListener接口後,必需要實現接口的三個方法,
     * onComplete  onCancel onError 
     *分別表示第三方登陸成功,取消 ,錯誤。*/
    private class BaseUiListener implements IUiListener {
 
        public void onCancel() {
            // TODO Auto-generated method stub
             
        }
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "登陸成功", 0).show();
            try {
                //得到的數據是JSON格式的,得到你想得到的內容
                //若是你不知道你能得到什麼,看一下下面的LOG
                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) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            /**到此已經得到OpneID以及其餘你想得到的內容了
            QQ登陸成功了,咱們還想獲取一些QQ的基本信息,好比暱稱,頭像什麼的,這個時候怎麼辦? 
            sdk給咱們提供了一個類UserInfo,這個類中封裝了QQ用戶的一些信息,我麼能夠經過這個類拿到這些信息 
            如何獲得這個UserInfo類呢?  */
            QQToken qqToken = mTencent.getQQToken();
            UserInfo info = new UserInfo(getApplicationContext(), qqToken);
            //這樣咱們就拿到這個類了,以後的操做就跟上面的同樣了,一樣是解析JSON    
     info.getUserInfo(new IUiListener() {
 
                public void onComplete(final Object response) {
                    // TODO Auto-generated method stub
                    Log.e(TAG, "---------------111111");
                    Message msg = new Message();
                    msg.obj = response;
                    msg.what = 0;
                    mHandler.sendMessage(msg);
                    Log.e(TAG, "-----111---"+response.toString());
                    /**因爲圖片須要下載因此這裏使用了線程,若是是想得到其餘文字信息直接
                     * 在mHandler裏進行操做
                     * 
                     */
                    new Thread(){
 
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            JSONObject json = (JSONObject)response;
                            try {
                                bitmap = Util.getbitmap(json.getString("figureurl_qq_2"));
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            Message msg = new Message();
                            msg.obj = bitmap;
                            msg.what = 1;
                            mHandler.sendMessage(msg);
                        }                       
                    }.start();
                }               
                public void onCancel() {
                    Log.e(TAG, "--------------111112");
                    // TODO Auto-generated method stub                  
                }
                public void onError(UiError arg0) {
                    // TODO Auto-generated method stub
                    Log.e(TAG, "-111113"+":"+arg0);
                }
                 
            });
             
        }
 
        public void onError(UiError arg0) {
            // TODO Auto-generated method stub
             
        }           
         
    }
    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) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }else if(msg.what == 1){
                Bitmap bitmap = (Bitmap)msg.obj;
                userlogo.setImageBitmap(bitmap);
                 
            }
        }
 
    };
 
     
}

\

上圖是登陸Q的返回LOG 測試

\

而後是AppConstant.java:

publicclassAppConstant {
    publicstaticString APP_ID="222222";
}



而後是Util.java
public class Util {
    public static String TAG="UTIL";
    public static Bitmap getbitmap(String imageUri) {
        Log.v(TAG, "getbitmap:" + imageUri);
        // 顯示網絡上的圖片
        Bitmap bitmap = null;
        try {
            URL myFileUrl = new URL(imageUri);
            HttpURLConnection conn = (HttpURLConnection) myFileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
 
            Log.v(TAG, "image download finished." + imageUri);
        } catch (IOException e) {
            e.printStackTrace();
            Log.v(TAG, "getbitmap bmp fail---");
            return null;
        }
        return bitmap;
    }
}
至此所有代碼就在這裏了,咱們得到了OpenID這個惟一標識最關鍵的東西,而後看項目中須要登陸的接口還須要什麼信息,獲取到就能實現登錄了
相關文章
相關標籤/搜索