Latest version (1.2.0) Easier, Lighter, More Business-Oriented
With the design goal of being simpler, lighter, and more oriented to business needs, it provides login and sharing function support for Weibo , WeChat , QQ , Tim , QQ chat version , and DingTalk ;
Project address: GitHub - SocialSdkLibrary
Blog address: Quick access to WeChat, Weibo, QQ and DingTalk native login and sharing
? The WeChatQQWeibo SDK version can be upgraded. When the next version is upgraded, Weibo will undergo major changes;
? 362 on 2020.1.21? La, released version 1.2.0
, plug-in update, supports the latest version of Gradle
, uses Gradle + APT + ASM
to automatically discover Platform
classes, automatically registers the initialization code, and has built-in json
parsing and http
requests, initialization Configuration is simpler;
? 2019.6.13 Support WeChat scan code login
? On May 28, 2019, the project received the 329th?, automatically managed the life cycle, unified callback parameters, and released stable version 1.0.1 ❤️,
? 2019.3.28 Use gradle plugin
to automatically manage dependencies, redesign the version number, stable version 0.1.1 ❤️
? 2018.12.27 Completed gradle
plug-in, split platform, automated dependencies, a new level?
? 2018.12.21 Already 225?, starting to prepare to split into different platform libraries to facilitate flexible access⛽️
? On September 26, 2018, the project received the 202nd star. Thanks to the new colleagues for supplementing 2 stars?
? On June 7, 2018, the project received the 100th stone?, and the last one was the one I asked my colleagues for?
? 2018.5.12 Fixed memory problem and extended function to stable version 1.1.0 ❤️
? 2018.2.12 Support DingTalk sharing?
? 2017.12.12 Simple refactoring of the code and testing the stable version 1.0.0 ❤️
Open source: no Easter eggs, no Easter eggs, no Easter eggs;
Simple: You only need to pay attention to the login, sharing management class and a data structure object, and there is no need to pay attention to the differences between platforms;
Lightweight: It only contains third-party SDK
and a simple asynchronous framework (38k). Network requests and JSON
parsing are injected from the outside, reducing redundant dependencies and ensuring a high degree of unity with the host project;
Comprehensive: sharing mini programs, copying links, scanning QR codes to log in, promoting intermodal transportation, etc.;
Design based on requirements:
code
locally, and the server gets token
?wxOnlyAuthCode
parameters;web
sharing for compatibility;Intent
to wake up sharing, such as supporting local video sharing, qq
plain text sharing, etc.;token
to avoid multiple authorizations. You can choose the validity period. The next time the token is authorized, the data can be obtained directly. However, if the user changes his WeChat account, he cannot switch accounts. This length of time should be carefully considered;SocialSdk
; STEP1 : Add plugin dependency path
project/build.gradle
buildscript {
repositories {
maven { url "https://dl.bintray.com/zfy/maven" }
}
dependencies {
// 请查看文初最新版本,这边可能忘记更新!!!
classpath 'com.zfy.social:social-sdk-plugin:1.2.0'
}
}
allprojects {
repositories {
maven { url "https://dl.bintray.com/zfy/maven" }
}
}
STEP2 : Configuration parameters
app/build.gralde
For security reasons, it is recommended to configure it in local.properties
, so as to avoid submitting it to the remote end;
// 在顶部引用插件
apply plugin: 'socialsdk'
// android 配置模块
android {
...
}
// socialsdk 配置模块
socialsdk {
wx {
appId = '111xxx2222'
appSecret = '111xxx2222'
// 微信授权是否只返回 code, 用于服务端授权的场景
onlyAuthCode = false
}
qq {
appId = '111xxx2222'
appSecret = '111xxx2222'
}
wb {
appId = '111xxx2222'
url = '111xxx2222'
}
dd {
appId = '111xxx2222'
}
}
The above is the simplest configuration. For more configuration parameters, please refer to the default configuration:
socialsdk {
// 调试模式,默认 false, 可以在代码中开启
debug = true
// 分享:选择停留在微信时自动返回成功,默认返回失败
shareSuccessIfStay = true
// 登录:token 过期时间,单位小时,默认立即过期,有效期内可以不需要再次唤醒第三方 app,但是二次登录也没办法切换账号,这会引发问题,所以默认立即过期
tokenExpiresHours = 100
// 使用 gson 作为数据解析,默认 true,你如果不用 gson 就需要自己编写 JSONAdapter
useGson = true
// 使用 okHttp 发送请求,默认 true,你如果不用 okhttp 就需要自己编写 RequestAdapter
useOkHttp = true
// 配置 app 名称,默认使用 R.string.app_name
appName = "哈哈哈"
// 唤醒过程中的 loading 颜色
color = "#FF0000"
wx { }
qq { }
wb { }
dd { }
}
STEP3 : Initialization
SocialOptions options = new SocialOptions . Builder ( this )
// 调试模式,开启 log 输出
. debug ( true )
// 加载缩略图失败时,降级使用资源图
. failImgRes ( R . drawable . share_default_img )
// 添加分享拦截器,重新处理分享的数据
. addShareInterceptor (( context , obj ) -> {
obj . setSummary ( "被重新组装" + obj . getSummary ());
return obj ;
})
// 构建
. build ();
// 初始化
SocialSdk . init ( options );
The login function supports three platforms, QQ, WeChat and Weibo;
// 3个平台
Target . LOGIN_QQ ; // QQ 登录
Target . LOGIN_WX ; // 微信 登录
Target . LOGIN_WX_SCAN ; // 微信扫码 登录
Target . LOGIN_WB ; // 微博 登录
Login will return LoginResult
, which mainly includes three parts: login type, basic user information, and token information;
LoginResult {
// 状态,成功,失败,取消等
public int state ;
// 目标平台
public int target ;
// 发生错误时使用
public SocialError error ;
// 针对登录类型可强转为 WbUser,WxUser,QQUser 来获取更加丰富的信息
public SocialUser socialUser ;
// 本次登陆的 token 信息,openId, unionId,token,expires_in
public AccessToken accessToken ;
// 授权码,如果 onlyAuthCode 为 true, 将会返回它
public String wxAuthCode ;
// 扫码登录二维码文件路径
public String wxCodePath ;
}
You need to set a login callback when logging in:
new OnLoginStateListener () {
@ Override
public void onState ( Activity act , LoginResult result ) {
switch ( result . state ) {
case LoginResult . STATE_START :
// 登录开始
break ;
case LoginResult . STATE_COMPLETE :
// 登录完成
break ;
case LoginResult . STATE_ACTIVE :
// 透明 Activity 开启
break ;
case LoginResult . STATE_SUCCESS :
// 登录成功
break ;
case LoginResult . STATE_FAIL :
// 登录失败
result . error
break ;
case LoginResult . STATE_CANCEL :
// 登录取消
break ;
case LoginResult . STATE_WX_CODE_RECEIVE :
// 获取到微信登录二维码
break ;
case LoginResult . STATE_WX_CODE_SCANNED :
// 微信登录二维码被扫描
break ;
}
}
};
Get more user information:
SocialUser socialUser = loginResult . socialUser ;
// 基本信息可以从 SocialUser 在获取到
String userNickName = socialUser . getUserNickName ();
// 获取 openId
String openId = socialUser . getOpenId ();
// 微信获取 unionId,其他平台仍旧返回 openId
String unionId = socialUser . getUnionId ();
// 获取 userId,微信返回 unionId, 其他平台返回 openId
String userId = socialUser . getUserId ();
// 强转为平台用户,可以拿到更多信息
int target = result . getTarget ();
switch ( target ) {
case Target . LOGIN_QQ :
QQUser qqUser = ( QQUser ) socialUser ;
break ;
case Target . LOGIN_WB :
WbUser wbUser = ( WbUser ) socialUser ;
break ;
case Target . LOGIN_WX :
WxUser wxUser = ( WxUser ) socialUser ;
break ;
}
Initiate login:
LoginManager . login ( mActivity , Target . LOGIN_QQ , listener );
Log in with parameters, such as scanning the WeChat QR code to log in:
LoginObj obj = new LoginObj ();
// 根据文档要求,以下数据应在服务端缓存获取
// 如果不设置,将会使用配置时设置的 secret
obj . setAppSecret ( "0a3cb00******ee3654f499171" );
obj . setNonceStr ( "3611cdc33b******a49ca45bdfab2d" );
obj . setTimestamp ( "15604******6904" );
obj . setSignature ( "b28f69426******18c8ba792caa4a0a1bcc" );
// 如果不设置,将会使用 SocialValues.WX_SCOPE
obj . setScope ( SocialValues . WX_SCOPE );
LoginManager . login ( mActivity , Target . LOGIN_WX_SCAN , obj , listener );
Regarding token
aging, you can set tokenExpiresHours
during initialization to control it. It also provides a method to clear the authorization token
.
// 清除全部平台的 token
LoginManager . clearAllToken ( context );
// 清除指定平台的 token
LoginManager . clearToken ( context , Target . LOGIN_QQ );
Important: Please carefully review the support capabilities between platforms and data types
When Weibo uses openApi
to share, there may be a long delay. It is recommended to add a progress bar display in the life cycle to avoid users waiting for a long time without responding.
For business logic and SDK
design, shared data types are divided into 7 types, which can cover most business scenarios, namely:
开启 App 类型,打开渠道应用;
文字类型,纯文本分享;
图片类型(jpg, png, gif(要求能动));
App 推广类型;
网页链接类型;
音频分享类型;
视频分享类型;
In order to ensure that each platform has a closed and unified appearance, if a platform is not compatible with a certain type of sharing, web
sharing will be used instead; for example, WeChat does not support app
sharing, and the web
sharing mode will be used after sharing.
// 支持的分享渠道
Target . SHARE_DD ; // 钉钉好友
Target . SHARE_QQ_FRIENDS ; // qq好友
Target . SHARE_QQ_ZONE ; // qq空间
Target . SHARE_WX_FRIENDS ; // 微信好友
Target . SHARE_WX_ZONE ; // 微信朋友圈
Target . SHARE_WX_FAVORITE ; // 微信收藏
Target . SHARE_WB ; // 新浪微博
Target . SHARE_SMS ; // 短信分享
Target . SHARE_EMAIL ; // 邮件分享
Target . SHARE_CLIPBOARD ; // 粘贴板分享
When sharing, we must first construct the data for sharing. The ShareObj
object provides a variety of static methods to quickly create objects corresponding to the type of sharing;
// 测试用的路径
localImagePath = new File ( Environment . getExternalStorageDirectory (), "1.jpg" ). getAbsolutePath ();
localVideoPath = new File ( Environment . getExternalStorageDirectory (), "video.mp4" ). getAbsolutePath ();
localGifPath = new File ( Environment . getExternalStorageDirectory (), "3.gif" ). getAbsolutePath ();
netVideoPath = "http://7xtjec.com1.z0.glb.clouddn.com/export.mp4" ;
netImagePath = "http://7xtjec.com1.z0.glb.clouddn.com/token.png" ;
netMusicPath = "http://7xtjec.com1.z0.glb.clouddn.com/test_music.mp3" ;
netMusicPath = "http://mp3.haoduoge.com/test/2017-05-19/1495207225.mp3" ;
targetUrl = "http://bbs.csdn.net/topics/391545021" ;
// 打开渠道对应app
ShareObj shareMediaObj = ShareObj . buildOpenAppObj ();
// 分享文字
ShareObj textObj = ShareObj . buildTextObj ( "分享文字" , "summary" );
// 分享图片
ShareObj imageObj = ShareObj . buildImageObj ( "分享图片" , "summary" , localImagePath );
// 分享gif
ShareObj imageGifObj = ShareObj . buildImageObj ( "分享图片" , "summary" , localGifPath );
// 分享app
ShareObj appObj = ShareObj . buildAppObj ( "分享app" , "summary" , localImagePath , targetUrl );
// 分享web
ShareObj webObj = ShareObj . buildWebObj ( "分享web" , "summary" , localImagePath , targetUrl );
// 分享视频
ShareObj videoObj = ShareObj . buildVideoObj ( "分享视频" , "summary" , localImagePath , targetUrl , localVideoPath , 10 );
// 本地视频分享、部分平台支持
ShareObj videoLocalObj = ShareObj . buildVideoObj ( "分享本地视频" , "summary" , localImagePath , targetUrl , localVideoPath , 0 );
// 分享音乐
ShareObj musicObj = ShareObj . buildMusicObj ( "分享音乐" , "summary" , localImagePath , targetUrl , netMusicPath , 10 );
Use extended parameter support for some parameters that cannot be unified:
// 使 ShareObj 支持短信分享
webObj . setSmsParams ( "13611301719" , "说啥呢" );
// 使 ShareObj 支持粘贴板分享
webObj . setClipboardParams ( "复制的内容" );
// 使 ShareObj 支持邮件分享
webObj . setEMailParams ( "[email protected]" , "主题" , "内容" );
// 使 ShareObj 在微信平台优先使用小程序分享
webObj . setWxMiniParams ( "51299u9**q31" , SocialValues . WX_MINI_TYPE_RELEASE , "/page/path" );
Use OnShareStateListener
as the listening sharing callback;
new OnShareStateListener () {
@ Override
public void onState ( Activity act , ShareResult result ) {
switch ( result . state ) {
case LoginResult . STATE_START :
// 分享开始
break ;
case LoginResult . STATE_COMPLETE :
// 分享完成
break ;
case LoginResult . STATE_ACTIVE :
// 透明 Activity 开启
break ;
case ShareResult . STATE_SUCCESS :
// 分享成功
break ;
case ShareResult . STATE_FAIL :
SocialError e = result . error ;
// 分享失败
break ;
case ShareResult . STATE_CANCEL :
// 分享取消
break ;
}
}
};
// 唤醒分享
ShareManager . share ( mActivity , Target . SHARE_QQ_FRIENDS , imageObj , mOnShareListener );
Regarding rewriting the sharing object, it actually provides an opportunity to uniformly process ShareObj
that needs to be shared before sharing, which is similar to an aspect of the sharing function, such as the following scenario:
app
watermark needs to be added to the picture before sharing it;url
carries public parameters such as shareId
etc., and access statistics are done in H5
; To rewrite shared objects, we use interceptors to achieve this. Interceptors are injected when SDK
is initialized. Multiple interceptors are supported and different businesses can be divided into different interceptors. All interceptors will be called sequentially;
UI
you need to execute it in the main thread;
SocialOptions options = new SocialOptions . Builder ( this )
// ... 其他初始化代码
// 添加分享拦截器
. addShareInterceptor (( context , target , obj ) -> {
obj . setSummary ( "描述加前缀" + obj . getSummary ());
return obj ;
})
. addShareInterceptor (( context , target , obj ) -> {
obj . setTargetUrl ( obj . getTargetUrl ()+ "?id=100" );
return obj ;
})
// 构建
. build ();
// 初始化
SocialSdk . init ( options );
We usually encounter requirements when sharing, such as copying to the pasteboard/supporting SMS sharing/supporting email sharing, etc. SocialSdk
has built-in these functions, and additional parameters need to be added after creating ShareObj
to implement them;
shareObj . setSmsParams ( "13611301719" , "说啥呢" );
shareObj . setEMailParams ( "[email protected]" , "主题" , "内容" );
shareObj . setClipboardParams ( "复制的内容" );
Support WeChat applet sharing, also using the form of additional parameters
shareObj . setWxMiniParams ( "51299u9**q31" , SocialValues . WX_MINI_TYPE_RELEASE , "/page/path" );
In order to better unify and share the exceptions returned when failure occurs, all exceptions returned will have a code
, which can locate problems and give more friendly prompts based on different code
.
int CODE_COMMON_ERROR = 101 ; // 通用错误,未归类
int CODE_NOT_INSTALL = 102 ; // 没有安装应用
int CODE_VERSION_LOW = 103 ; // 版本过低,不支持
int CODE_SHARE_BY_INTENT_FAIL = 105 ; // 使用 Intent 分享失败
int CODE_STORAGE_READ_ERROR = 106 ; // 没有读存储的权限,获取分享缩略图将会失败
int CODE_STORAGE_WRITE_ERROR = 107 ; // 没有写存储的权限,微博分享视频copy操作将会失败
int CODE_FILE_NOT_FOUND = 108 ; // 文件不存在
int CODE_SDK_ERROR = 109 ; // sdk 返回错误
int CODE_REQUEST_ERROR = 110 ; // 网络请求发生错误
int CODE_CANNOT_OPEN_ERROR = 111 ; // 无法启动 app
int CODE_PARSE_ERROR = 112 ; // 数据解析错误
int CODE_IMAGE_COMPRESS_ERROR = 113 ; // 图片压缩失败
int CODE_PARAM_ERROR = 114 ; // 参数错误
int CODE_SDK_INIT_ERROR = 115 ; // SocialSdk 初始化错误
int CODE_PREPARE_BG_ERROR = 116 ; // 执行 prepareOnBackground 时错误
int CODE_NOT_SUPPORT = 117 ; // 不支持
For example you can do this:
listener = new OnShareStateListener () {
@ Override
public void onState ( Activity act , ShareResult result ) {
switch ( result . state ) {
case ShareResult . STATE_FAIL :
SocialError e = result . error ;
showMsg ( "分享失败 " + e . toString ());
// 如下因为没有存储权限导致失败,请求权限
if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . M ) {
if ( e . getCode () == SocialError . CODE_STORAGE_READ_ERROR ) {
requestPermissions ( new String []{ Manifest . permission . READ_EXTERNAL_STORAGE }, 100 );
} else if ( e . getCode () == SocialError . CODE_STORAGE_WRITE_ERROR ) {
requestPermissions ( new String []{ Manifest . permission . WRITE_EXTERNAL_STORAGE }, 100 );
}
}
break ;
}
}
};
public class HuaweiPlatform extends AbsPlatform {
// 工厂函数
public static class Factory implements PlatformFactory {
@ Override
public IPlatform create ( Context context , int target ) {
return new HuaweiPlatform ( context , null , null , target );
}
@ Override
public int getPlatformTarget () {
return PLATFORM_HUAWEI ;
}
@ Override
public boolean checkShareTarget ( int shareTarget ) {
return false ;
}
@ Override
public boolean checkLoginTarget ( int loginTarget ) {
return loginTarget == LOGIN_HUAWEI ;
}
}
public HuaweiPlatform ( Context context , String appId , String appName , int target ) {
super ( context , appId , appName , target );
}
}
The most important thing is to write the factory function of the platform. The framework will automatically discover and register it in the system. There is no need to register manually;
SocialSdk
has automatic management of the life cycle internally. All resources will be recycled after each login sharing is completed. It is recommended that Activity
initiates login sharing implement LifecycleOwner
interface. AppCompatActivity
can be used directly, and the life cycle will be bound internally to avoid memory leaks. occurrence;
QQ:
libs/open_sdk_r2973327_lite.jar
updated with 2019.12WeChat:
com.tencent.mm.opensdk:wechat-sdk-android-without-mta:5.5.8
updated with 2020.1.22Weibo:
com.sina.weibo.sdk:core:4.3.7:openDefaultRelease@aar
DingTalk:
com.alibaba.android:ddsharesdk:1.1.0