Android使用ShareSDK集成QQ、微信、微博等第三方登录

转载请注明出处:http://www.jianshu.com/p/c104fa307c60

前言

第三方登录几乎是每个APP的必须功能。有些人说看官方的文档实在让人眼花缭乱,以前自己第一次做这些功能的时候也会遇到很多坑。这里整理了一份比较详细的,主要给新手学习。有任何问题欢迎提出来!

1、获取ShareSDK的AppKey

(照着流程来,很简单!)
http://bbs.mob.com/forum.php?mod=viewthread&tid=8212&extra=page%3D1

2、下载SDK

下载地址:http://www.mob.com/downloadDetail/ShareSDK/android
下载的时候一般用默认的就足够了

下载后解压出来是这样的


3、准备资源

点击第一个文件夹,进去如下,双击QuickIntegrater.jar


只需要填写项目名称和项目包名即可,其他默认。如图:


点击确认后会生成如下文件夹,如图:


4、开始集成

1,将上面的文件夹依次粘贴到工程相应的文件夹即可,如图:

2,在清单文件AndroidManifest.xml添加权限

<uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS"/>
    <uses-permission android:name="android.permission.GET_ACCOUNTS"/>
    <!-- 蓝牙分享所需的权限 -->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

3,在清单文件AndroidManifest.xml添加activity信息

(注意:tencent后面的appid要保持和您配置的QQ的appid一致)

<activity
     android:name="com.mob.tools.MobUIShell"
     android:theme="@android:style/Theme.Translucent.NoTitleBar"
     android:configChanges="keyboardHidden|orientation|screenSize"
     android:screenOrientation="portrait"
     android:windowSoftInputMode="stateHidden|adjustResize" >

     <intent-filter>
         <data android:scheme="tencent100371282" />
         <action android:name="android.intent.action.VIEW" />
         <category android:name="android.intent.category.BROWSABLE" />
         <category android:name="android.intent.category.DEFAULT" />
     </intent-filter>

    <!-- 调用新浪原生SDK,需要注册的回调activity -->
    <intent-filter>
        <action android:name="com.sina.weibo.sdk.action.ACTION_SDK_REQ_ACTIVITY" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>

    <!--集成line客户端登录授权,需要添如下格式的过滤器-->
    <intent-filter> 
    <data android:scheme="line.1477692153" />
    <action android:name="android.intent.action.VIEW"/>
    <category android:name="android.intent.category.BROWSABLE" />
    <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>

 </activity>

如果您集成了微信,还需要添加下面回调的activity处理;

<activity
     android:name=".wxapi.WXEntryActivity"
     android:theme="@android:style/Theme.Translucent.NoTitleBar"
     android:configChanges="keyboardHidden|orientation|screenSize"
     android:exported="true"
     android:screenOrientation="portrait" /> 

4,在刚刚拷贝进去的ShareSDK中替换mob后台申请的Appkey与各个平台申请的key

注意:
mob后台申请的Appkey:就是第一部中获取ShareSDK的AppKey
各个平台申请的key:需要到各个平台申请,例如需要微信分享,则需要到微信开放平台进行申请

5,添加登录代码

1,在您程序启动的时候添加初始化代码(注:不要等调用ShareSDK功能之前才初始化)
即自己添加一个类继承Application,在onCreate方法添加下面的代码,如下:

package com.xinhao.thirdpartysharelogin;

import android.app.Application;

import cn.sharesdk.framework.ShareSDK;

/**
 * author           Alpha58
 * date             2017/03/15
 * desc             ${Application}
 * <p>
 * upDateAuthor     $Author$
 * upDate           $Date$
 * upDateDesc       ${TODO}
 */
public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        //初始化ShareSDK
        ShareSDK.initSDK(this);
    }
}

注意: 该类需要在清单文件中注册,如图:


2,登录activity代码

package com.xinhao.thirdpartysharelogin;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.mob.tools.utils.UIHandler;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

import static android.R.attr.action;


/**
 * author           Alpha58
 * date             2017/03/16
 * desc             ${第三方登录}
 * <p>
 * upDateAuthor     $Author$
 * upDate           $Date$
 * upDateDesc       ${TODO}
 */
public class LoginActivity extends Activity implements PlatformActionListener, Handler.Callback, View.OnClickListener {

    private static final int MSG_ACTION_CCALLBACK = 0;
    private ImageView ivWxLogin;
    private ImageView ivQqLogin;
    private ImageView ivBlog;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        initListener();
        initData();
    }


    public void initView() {
        ivWxLogin = (ImageView) findViewById(R.id.iv_wx_login);
        ivQqLogin = (ImageView) findViewById(R.id.iv_qq_login);
        ivBlog = (ImageView) findViewById(R.id.iv_blog);
    }


    public void initListener() {
        ivWxLogin.setOnClickListener(this);
        ivQqLogin.setOnClickListener(this);
        ivBlog.setOnClickListener(this);
    }


    public void initData() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_wx_login:
                Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                wechat.setPlatformActionListener(this);
                wechat.SSOSetting(false);
                authorize(wechat, 1);
                break;
            case R.id.iv_qq_login:
                Platform qq = ShareSDK.getPlatform(QQ.NAME);
                qq.setPlatformActionListener(this);
                qq.SSOSetting(false);
                authorize(qq, 2);
                break;
            case R.id.iv_blog:
                Platform sina = ShareSDK.getPlatform(SinaWeibo.NAME);
                sina.setPlatformActionListener(this);
                sina.SSOSetting(false);
                authorize(sina, 3);
                break;
            default:
                break;
        }

    }

    //授权
    private void authorize(Platform plat, int type) {
        switch (type) {
            case 1:
                showProgressDialog(getString(R.string.opening_wechat));
                break;
            case 2:
                showProgressDialog(getString(R.string.opening_qq));
                break;
            case 3:
                showProgressDialog(getString(R.string.opening_blog));
                break;
        }
        if (plat.isValid()) { //如果授权就删除授权资料
            plat.removeAccount();
        }
        plat.showUser(null);//授权并获取用户信息
    }

    //登陆授权成功的回调
    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> res) {
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 1;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);   //发送消息

    }

    //登陆授权错误的回调
    @Override
    public void onError(Platform platform, int i, Throwable t) {
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 2;
        msg.arg2 = action;
        msg.obj = t;
        UIHandler.sendMessage(msg, this);
    }

    //登陆授权取消的回调
    @Override
    public void onCancel(Platform platform, int i) {
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 3;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);
    }

    //登陆发送的handle消息在这里处理
    @Override
    public boolean handleMessage(Message message) {
        hideProgressDialog();
        switch (message.arg1) {
            case 1: { // 成功
                Toast.makeText(LoginActivity.this, "授权登陆成功", Toast.LENGTH_SHORT).show();

                //获取用户资料
                Platform platform = (Platform) message.obj;
                String userId = platform.getDb().getUserId();//获取用户账号
                String userName = platform.getDb().getUserName();//获取用户名字
                String userIcon = platform.getDb().getUserIcon();//获取用户头像
                String userGender = platform.getDb().getUserGender(); //获取用户性别,m = 男, f = 女,如果微信没有设置性别,默认返回null
                Toast.makeText(LoginActivity.this, "用户信息为--用户名:" + userName + "  性别:" + userGender, Toast.LENGTH_SHORT).show();

                //下面就可以利用获取的用户信息登录自己的服务器或者做自己想做的事啦!
                //。。。

            }
            break;
            case 2: { // 失败
                Toast.makeText(LoginActivity.this, "授权登陆失败", Toast.LENGTH_SHORT).show();
            }
            break;
            case 3: { // 取消
                Toast.makeText(LoginActivity.this, "授权登陆取消", Toast.LENGTH_SHORT).show();
            }
            break;
        }
        return false;
    }

    //显示dialog
    public void showProgressDialog(String message) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(message);
        progressDialog.setCancelable(true);
        progressDialog.show();
    }

    //隐藏dialog
    public void hideProgressDialog() {
        if (progressDialog != null)
            progressDialog.dismiss();
    }

}

3,布局activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="center"
              android:orientation="horizontal"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <ImageView
            android:id="@+id/iv_wx_login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="10dp"
            android:clickable="true"
            android:src="@mipmap/wechat_icon"
            />

        <ImageView
            android:id="@+id/iv_qq_login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="10dp"
            android:clickable="true"
            android:src="@mipmap/qq_icon"
            />

        <ImageView
            android:id="@+id/iv_blog"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="10dp"
            android:clickable="true"
            android:src="@mipmap/blog_icon"
            />


    </LinearLayout>


</LinearLayout>

效果如下:

Demo下载:https://github.com/wildma/ShareSDKThirdPartyShareLogin

如果对你有帮助记得点赞,star支持下哈~



作者:wildma
链接:https://www.jianshu.com/p/c104fa307c60
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:上身试试 返回首页