Android 第三方QQ、微信、微博登录分享

最近弄了下QQ微信微博的登录分享,在这里做一下总结,以下登录分享使用的都是官方的最新SDk。

首先是QQ的登录:

1.第一步肯定是先去开放平台注册应用,这里步骤就不详细说了 http://open.qq.com/

2.将下载好的jar包导入工程,在AndroidManifest文件里面注册SDK里面提供的Activity

<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>

<activity
    android:name="com.tencent.connect.common.AssistActivity"
    android:configChanges="orientation|keyboardHidden|screenSize"
    android:theme="@android:style/Theme.Translucent.NoTitleBar" />
到这里前期的准备工作就全部做好了

3.首先写一个类实现IUiListener接口作为登录后的回调

public class BaseUiListener implements IUiListener {
    @Override
    public void onComplete(Object o) {
        Toast.makeText(MyFragmentActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(UiError uiError) {
        Toast.makeText(MyFragmentActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCancel() {
        Toast.makeText(MyFragmentActivity.this, "取消登录", Toast.LENGTH_SHORT).show();
    }
}
4.接下来开始写登录代码了

private Tencent mTencent;

mTencent = Tencent.createInstance("AppId", this);
if (!mTencent.isSessionValid()) {
    mTencent.login(this, "all", myFragmentActivity.baseUiListener);
}
里面的all代表你需要获取的权限

5.重写onActivityResult方法

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Constants.ACTIVITY_OK) {
        if (requestCode == Constants.REQUEST_LOGIN) {
            if (baseUiListener != null)
                Tencent.onActivityResultData(requestCode, resultCode, data, baseUiListener);
        } else if (requestCode == Constants.REQUEST_OLD_SHARE) {
            if (shareListener != null)
                Tencent.onActivityResultData(requestCode, resultCode, data, shareListener);
        } 
    }
}
里面包括了分享的回调,登录到这就全部做好了,但是一般登录后都需要获取用户信息,只需要将以下代码放在登录成功的回调里面就可以了

if (setDataListener != null) {
    try {
        JSONObject data = (JSONObject) o;
        String openID = data.getString("openid");
        String accessToken = data.getString("access_token");
        String expires = data.getString("expires_in");
        mTencent.setOpenId(openID);
        mTencent.setAccessToken(accessToken, expires);
        UserInfo userInfo = new UserInfo(getActivity(), mTencent.getQQToken());
        userInfo.getUserInfo(iUiListener);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
里面的iUiListener是获取用户信息的回调

private IUiListener iUiListener = new IUiListener() {
    @Override
    public void onComplete(Object o) {
        if (o != null) {
            Toast.makeText(getActivity(), o.toString(), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getActivity(), "获取信息为空", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onError(UiError uiError) {
        Toast.makeText(getActivity(), "获取信息失败", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onCancel() {

    }
};

QQ分享

QQ的分享比较简单,直接贴代码

private void share() {
        Bundle bundle = new Bundle();
//这条分享消息被好友点击后的跳转URL。
        bundle.putString(QQShare.SHARE_TO_QQ_TARGET_URL, "http://connect.qq.com/");
//分享的标题。注:PARAM_TITLE、PARAM_IMAGE_URL、PARAM_   SUMMARY不能全为空,最少必须有一个是有值的。
        bundle.putString(QQShare.SHARE_TO_QQ_TITLE, "我在测试");
//分享的图片URL
        bundle.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,
                "http://img3.cache.netease.com/photo/0005/2013-03-07/8PBKS8G400BV0005.jpg");
//分享的消息摘要,最长50个字
        bundle.putString(QQShare.SHARE_TO_QQ_SUMMARY, "测试");

        mTencent.shareToQQ(this, bundle,new ShareListener());
    }
public class ShareListener implements IUiListener {
    @Override
    public void onComplete(Object o) {
        Toast.makeText(MyFragmentActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(UiError uiError) {
        Toast.makeText(MyFragmentActivity.this, "分享失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCancel() {
        Toast.makeText(MyFragmentActivity.this, "取消分享", Toast.LENGTH_SHORT).show();
    }
}
微信登录

由于微信的回调有所不同,所以这里登录分享一起弄,还有微信的登录分享都只能在安装了微信客户端的情况下才能使用

1.第一步同样去注册应用信息 https://open.weixin.qq.com/

2.下载SDk导入工程

3.在你的包名相应目录下新建一个wxapi目录,并在该wxapi目录下新增一个WXEntryActivity类,该类继承自Activity并实现IWXAPIEventHandler接口

Android 第三方QQ、微信、微博登录分享_第1张图片

4.注册这个Activity

<activity
    android:name=".wxapi.WXEntryActivity"
    android:exported="true" />

准备工作到这里也就全部做完了

5.接下来贴登录代码

private IWXAPI iwxapi;
iwxapi = WXAPIFactory.createWXAPI(this, "AppId");
if (!iwxapi.isWXAppInstalled()) {
    Toast.makeText(getActivity(), "请先安装微信应用", Toast.LENGTH_SHORT).show();
    break;
}
iwxapi.registerApp("");
SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";//需要的权限范围
req.state = "wechat_sdk_demo_test";
iwxapi.sendReq(req);

6.接下来贴上分享代码

private void weixShare() {
    WXWebpageObject wxWebpageObject = new WXWebpageObject();
    wxWebpageObject.webpageUrl = "https://www.baidu.com/";

    WXMediaMessage message = new WXMediaMessage(wxWebpageObject);
    message.title = "百度哦";
    message.description = "这是百度";
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a);
    message.setThumbImage(bitmap);

    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = buildTransaction("webpage");
    req.message = message;
    //发送到聊天界面WXSceneSession 发送到朋友圈WXSceneTimeline
    req.scene = SendMessageToWX.Req.WXSceneSession;
    iwxapi.sendReq(req);
}
7.接下来就是在WXEntryActivity类里面处理的回调,先直接把代码全部贴出

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // handleIntent(intent);
        api= WXAPIFactory.createWXAPI(this, "AppId");
        api.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        String result = "";
        int type = baseResp.getType();
        String typeString = "";
        //type=1表示登录,type=2表示分享
        if (type==1){
            typeString = "登录";

            if (baseResp.errCode == BaseResp.ErrCode.ERR_OK) {
                //用户同意
                String code = ((SendAuth.Resp) baseResp).code;
                Intent goMain = new Intent(this, MyFragmentActivity.class);
                goMain.putExtra("code", code);
                startActivity(goMain);
            }
        }else if (type==2){
            typeString = "分享";
        }
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                Log.i("onResp", "调用了WXEntryActivity中的onResp方法");
                result = typeString+"成功";
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = typeString+"分享";
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = typeString+"被服务器拒绝";
                break;
            default:
                result = "未知操作";
                break;
        }
        Toast.makeText(this, result, Toast.LENGTH_LONG).show();
        this.finish();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
       // handleIntent(intent);
        api.handleIntent(intent, this);
    }

    private void handleIntent(Intent intent) {
        SendAuth.Resp resp = new SendAuth.Resp(intent.getExtras());
        if (resp.errCode == BaseResp.ErrCode.ERR_OK) {
            //用户同意
            String code = resp.code;
            Intent goMain = new Intent(this, MyFragmentActivity.class);
            intent.putExtra("code", code);
            startActivity(goMain);
        }
    }
}
这里我一开始使用的是自己写的hanleIntent方法绑定回调,结果发现无法区分产生的回调是登录的回调还是分享的回调,得到的type都是1,所以用了另一种方法。

微信的登录分享到这里就全部解决了


微博

登录

最新版的Sdk只能支持有客户端的情况下登录,这是官方文档里面的两段话



由于使用最新版本的SDk所以这里就只写sso登录

1.首先也一样去注册应用 http://open.weibo.com/

2.因为我现在使用的是studio开发,所以导入jar包的方式有点不同

首先我将

做为model导入工程

然后

Android 第三方QQ、微信、微博登录分享_第2张图片

Android 第三方QQ、微信、微博登录分享_第3张图片

就这样导入工程,到这准备工作就做好了

3.贴上登录代码

AuthInfo authInfo = new AuthInfo(getActivity(), WeiBoConstants.APP_KEY, WeiBoConstants.REDIRECT_URL, WeiBoConstants.SCOPE);
SsoHandler mSsoHandler = new SsoHandler(getActivity(), authInfo);
mSsoHandler.authorize(new AuthListener());
class AuthListener implements WeiboAuthListener {

    @Override
    public void onComplete(Bundle bundle) {
        Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onWeiboException(WeiboException e) {
        Toast.makeText(getActivity(), "登录失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCancel() {
        Toast.makeText(getActivity(), "取消登录", Toast.LENGTH_SHORT).show();
    }
}
这个也需要重写onActivityResult方法

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Constants.ACTIVITY_OK) {
        if (requestCode == Constants.REQUEST_LOGIN) {
            if (baseUiListener != null)
                Tencent.onActivityResultData(requestCode, resultCode, data, baseUiListener);
        } else if (requestCode == Constants.REQUEST_OLD_SHARE) {
            if (shareListener != null)
                Tencent.onActivityResultData(requestCode, resultCode, data, shareListener);
        } else {
            if (requestCode == 32973)//这个是微博的requestCode值,不知道为什么没有把它暴露出来
                if (mSsoHandler != null) {
                    mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
                }
        }
    }
}
登录到这里就做好了,接下来是分享

分享需要在你接收分享回调信息的Activity中加上

<intent-filter>

     <action android:name="com.sina.weibo.sdk.action.ACTION_SDK_REQ_ACTIVITY" />

     <category android:name="android.intent.category.DEFAULT" />

</intent-filter>

例如

<activity android:name=".WeiBoShareActivity" >
    <intent-filter>
        <action android:name="com.sina.weibo.sdk.action.ACTION_SDK_REQ_ACTIVITY" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

接下来贴上分享的代码

private IWeiboShareAPI mWeiboShareAPI;


mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, WeiBoConstants.APP_KEY);

//下面这端代码需要放在onCreate里面
if (savedInstanceState != null) {
    mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
}
private void weiBoShare() {

    mWeiboShareAPI.registerApp();
    ImageObject imageObject = new ImageObject();
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    imageObject.setImageObject(bitmap);
    TextObject textObject = new TextObject();
    textObject.text = "https://www.baidu.com/";
    WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
    weiboMessage.textObject =textObject;
    //  weiboMessage.mediaObject = imageObject;
    SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
    request.transaction = String.valueOf(System.currentTimeMillis());
    request.multiMessage = weiboMessage;
    mWeiboShareAPI.sendRequest(this,request);
}
需要重写onNewIntent方法

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    mWeiboShareAPI.handleWeiboResponse(intent, this);
}
进行分享的Activity实现IWeiboHandler.Response接口

@Override
public void onResponse(BaseResponse baseResponse) {
    switch (baseResponse.errCode) {
        case WBConstants.ErrorCode.ERR_OK:
            Toast.makeText(this, "分享成功", Toast.LENGTH_SHORT).show();
            break;
        case WBConstants.ErrorCode.ERR_CANCEL:
            Toast.makeText(this, "取消分享", Toast.LENGTH_SHORT).show();
            break;
        case WBConstants.ErrorCode.ERR_FAIL:
            Toast.makeText(this, "分享失败", Toast.LENGTH_SHORT).show();
            break;
    }
}

到这里微博分享也就全部搞好了

需要注意的是

public static final String REDIRECT_URL = "http://www.sina.com";
设置的回调页要在

Android 第三方QQ、微信、微博登录分享_第4张图片

写上,要不让会出现网络错误的情况

你可能感兴趣的:(android,微博,qq,微信,第三方登录分享)