使用腾讯开发平台获取QQ用户数据资料
in Android with 0 comment
Read: 934

使用腾讯开发平台获取QQ用户数据资料

in Android with 0 comment

本博客为以前小编发布至博客园中的文章,现转到自己个人网站

原网址:http://www.cnblogs.com/boy1025/p/4744999.html

今天是七夕:祝大家七夕嗨皮,前可么么哒,后可啪啪啪
Tips:本篇博客将教你如何使用腾讯开发平台获取QQ用户资料


正文

在这篇博客中,我们将使用QQ登陆,以及获取资料,所以我们使用的API为SDK API 以及Open API

进入Tencent wiki获取相关帮助文档

编码

在这里我们的主要描述—>登陆—>获取用户的Openid等数据—>解析出Openid等数据->通过Openid等数据获取用户资料

package com.example.loginbyqq;

import android.content.Context;

import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;
/**
 * @author monster
 * @category BaseUiListener 进行信息的回调
 */
public class BaseUiListener implements IUiListener{
        
    @SuppressWarnings("unused")
    private Context mContext;
    @SuppressWarnings("unused")
    private String mScope;
    

    
    public BaseUiListener(){
        super();
    }
    
    public BaseUiListener(Context mContext) {
        super();
        this.mContext = mContext;
    }
    
    public BaseUiListener(Context mContext, String mScope) {
        super();
        this.mContext = mContext;
        this.mScope = mScope;
    }
    
    @Override
    public void onCancel() {
        //Log.e("TAG-->Cancel", "Cancel");
    }
    @Override
    public void onComplete(Object object) {
        //Log.e("TAG-->Complete", ""+object);    

    }
    @Override
    public void onError(UiError error) {
        //Log.e("TAG-->Error", ""+error);
    }
    
    
}
package com.example.loginbyqq;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;

@SuppressLint("HandlerLeak")
public class MainActivity extends Activity implements OnClickListener{

    private Button btn_LoginQQ;
    private Tencent mTencent;
    public String APP_ID = "Your APPID";
    
    private TextView user_nickname;
    private ImageView user_photo;
    
    private IUiListener listener;
    private String nickName , figureurl;

    private static final int SUCCESS = 0;
    private static final int FAILED = 1;
    
    private Handler mHandler=new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case SUCCESS:
                String nick=(String) msg.obj;
                user_nickname.setText(nick);
                break;
            case FAILED:
                Toast.makeText(MainActivity.this, "获取数据失败", Toast.LENGTH_SHORT).show();
                break;
            }
        };
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTencent = Tencent.createInstance(APP_ID, this.getApplicationContext()); //实例化对象
        initView();
    }
    /**
     * 初始化视图
     */
    private void initView() {
        btn_LoginQQ=(Button) findViewById(R.id.btn_LoginQQ);
        btn_LoginQQ.setOnClickListener(this);
        user_photo=(ImageView) findViewById(R.id.user_logo);
        user_nickname=(TextView) findViewById(R.id.user_nickname);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_LoginQQ:
                login();
            break;
        }
    }
    

    /**
     * 登陆
     */
    private void login() {
        mTencent = Tencent.createInstance(APP_ID, this.getApplicationContext());  //创建实例
        if(!mTencent.isSessionValid()){
            listener=new BaseUiListener(){
                @Override
                public void onComplete(Object object) {
                    JSONObject json = (JSONObject) object;
                    getUserInfoByVolley(json);
                }
            };
            mTencent.login(this, "all", listener);
            
        }
    }

    /**
     * 使用Volley解析json数据
     * @param json
     */

    protected void getUserInfoByVolley(JSONObject json) {
        try {
            String openid=json.getString("openid");
            String access_token=json.getString("access_token");
            Log.e("TAG--->Openid",openid);
            Log.e("TAG--->Openid",access_token);
            
            String url="http://119.147.19.43/v3/user/get_info?openid="+openid+"&openkey="+access_token+"&pf=qzone&appid=1104812858&format=json&userip=10.0.0.1&sig=C3BGTm24S%2FZJdt1J%2BjfEzRpCLWA%3D"; 
            /**
             * 使用Volley框架得到json数据
             * tag : https://github.com/adamrocker/volley
             */
            
            RequestQueue requestQueue=Volley.newRequestQueue(MainActivity.this); //用于获取一个Volley的请求对象
             JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, 
                     new Response.Listener<JSONObject>() {
                             @Override
                             public void onResponse(JSONObject json) {
                             /**
                              * 解析json数据
                              */
                                 try {
                                     nickName=json.getString("nickname");  //昵称
                                     figureurl=json.getString("figureurl");  //头像的url
                                     
                                     //TODO 通过异步任务处理图片
                                     new NewAsyncTask().execute(figureurl);
                                     //
                                     
                                     mHandler.obtainMessage(SUCCESS, nickName).sendToTarget();
                                     
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                             }
                        }, 
                    new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError arg0) {
                                Log.e("error","问题~~");
                                mHandler.obtainMessage(FAILED).sendToTarget();
                            }
                    });
             requestQueue.add(jsonObjectRequest); //在请求队列中加入当前的请求
             
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 异步任务加载图片
     * @author monster
     */
    class NewAsyncTask extends AsyncTask<String, Void, Bitmap>{

        @Override
        protected Bitmap doInBackground(String... params) {
            String url=params[0];
            return getBitmapByUrl(url);
        }
        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            user_photo.setImageBitmap(result);
        }
        
    }

    /**
     * 通过url 得到bitmap对象
     * @param urlString
     * @return
     */
    public Bitmap getBitmapByUrl(String urlString) {
        Bitmap bitmap;
        InputStream is = null;
        try {
            URL url=new URL(urlString);
            HttpURLConnection connection=(HttpURLConnection) url.openConnection();
            is=new BufferedInputStream(connection.getInputStream());
            bitmap=BitmapFactory.decodeStream(is);
            connection.disconnect(); //关闭连接
            return bitmap;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                is.close();  
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.loginbyqq"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.loginbyqq.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
           <activity
                android:name="com.tencent.tauth.AuthActivity"
                android:noHistory="true"
                android:launchMode="singleTask" >
                    <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="tencentYOURAPPID" />
                    </intent-filter>
            </activity>
           <activity
                android:name="com.tencent.connect.common.AssistActivity"
                android:theme="@android:style/Theme.Translucent.NoTitleBar"
                android:configChanges="orientation|keyboardHidden|screenSize"/> 
    </application>
</manifest>

总结

用户需要进行登录,然后通过登录得到用户的数据Object,然后解析Object,解析完成后,在通过Openid,Access_Token,使用APi得到对象的用户json数据(这里的解析使用的Volley框架) , 得到json数据后在进行解析,解析成功后在进行对应的赋值,赋值的时候本文处理是:

昵称使用的Thread+Handler进行处理,图片使用AsyncTask进行处理,在这里小编要特别提醒,小编在虚拟机测试不通过,在真机测试通过,原因在与虚拟机没有安装手机QQ,但是,貌似可以通过web端进行登录,这里小编没有细研究..,关于头像的大小问题,请看链接

源码

点我下载

Responses