Access with the native SDK of Weibo, QQ, wechat and Dingding.com to provide login and sharing function support of these platforms. The interface of each platform is encapsulated according to the business logic to provide consistent performance externally, which not only reduces the access pressure, but also achieves the maximum flexibility of the native SDK.

Considering that the SDK of each platform is also constantly updated, and the requirements of each project are quite different. For example, it may only need to support part of the platform, so the class library is not released. Please download the Module on GitHub to rely on it by yourself. You only need to delete the corresponding implementation under the Platform package, which does not affect other platforms.

Github-SocialsdkLibrary

This address: fast access to wechat weibo QQ nail native login to share

🎉 2017.12.12 Simple refactoring and testing of the code, first stable release 1.0.0

🎉 2018.2.12 Share by Nails



advantages

Still optimizing…

🔥 Simple: Just focus on a few management classes and the construction of related data to achieve the required functionality, without the need to worry about complex authorization and sharing logic.

🔥 Lightweight: In addition to the required third-party SDKS, this project relies only on the framework bolts (38K) of a simple asynchronous task. This will be removed later to avoid unnecessary dependencies and ensure a high degree of integration with the host project.

🔥 Comprehensive: Stores authorization tokens internally, avoiding multiple authorization. Qq, wechat, Weibo to do a perfect support;

🔥 scalability:

  • Platform independence, the project is divided by platform, each platform is completely independent, if you want to support only part of the platform, you only need to deleteplatformPackage under the specific implementation of the platform.
  • Requests, JSON parsing, and other functions can be externally injected into the proxy, with custom extensions to some functions.
  • Can inheritAbsPlatformAccess other platforms to share and customize extensions.

🔥 functionality: Extends to actual project requirements, such as providing an opportunity to reconstruct shared data before sharing.

🔥 Compatibility:

  • Provides a sharing interface with the same appearance for multiple platforms. If no, use this interfacewebShare compatibility.
  • Support direct use of network photo sharing, built-in automatic download function.
  • useIntentCompatible with unsupported data modes, such as local video sharing,qqPure text sharing and so on.

Main class file

To use SocialSdk, you only need to pay attention to the following files:

👉️ Socialsdk. Java Combines socialconfig. Java to configure authorization information.

The 👉️ target. Java class is a separate constant class that points to specific targets for login and sharing.

👉️ loginManager.java is used to implement third-party authorized login of QQ, wechat, and Weibo, and store accessToken internally. No multiple authorization is required, just call loginManager.login ().

👉️️ shareManager.java is used to share 8 data types, 4 platforms, and 8 channels by calling shareManager.share ().

Gradle configuration

When you rely on the class library, it will automatically merge. Yet, you still need to configure the Manifestplaceholder qqId in your app/build.gradle project. The code is as follows:

defaultConfig {
	manifestPlaceholders = [qq_id: "11049xxxxx"]}Copy the code

About the use of the Manifestplaceholder

When you use the manifestplaceholder ="11049xxxxx"When it is declared, all the manifestplaceholder will be replaced, and only the last one will remain. When you use manifestplaceholder. Qq_id ="11049xxxxx"When it comes to the original manifestplaceholder, it will append a new product to it while preserving the previous one. The recommended approach is to use direct assignment in defaultConfig and append to buildTypes and Favors to avoid overwriting the previous ones.Copy the code

Initialize the

You need to do this before using the SDK. It is recommended to do this in Applicaton.

String qqAppId = getString(R.string.QQ_APPID);
String wxAppId = getString(R.string.WEICHAT_APPID);
String wxSecretKey = getString(R.string.WEICHAT_APPKEY);
String sinaAppId = getString(R.string.SINA_APPKEY);
String ddAppId = getString(R.string.DD_APPID);
SocialSdkConfig config = new SocialSdkConfig(this)
        .dd(ddAppId)
        Qq / / configuration
        .qq(qqAppId)
        Wx / / configuration
        .wechat(wxAppId, wxSecretKey)
        Sina / / configuration
        .sina(sinaAppId)
        // Sina RedirectUrl (Sina RedirectUrl) has a default value
        .sinaRedirectUrl("http://open.manfenmm.com/bbpp/app/weibo/common.php")
        // Sina authorization scope is configured. The default value is all
        .sinaScope(SocialConstants.SCOPE);
// 👮 Add config data, required
SocialSdk.init(config);
// 👮 to add custom JSON parsing, required
SocialSdk.setJsonAdapter(new GsonJsonAdapter());
Copy the code

adapter

The Adapter pattern is based on mature libraries to provide better extensibility. Look at SocialSDK.java.

  • The IJsonAdapter, which is responsible for Json parsing, must be customized to maintain consistency with the host project’s Json parsing framework (there is no built-in implementation because it is too cumbersome to use native JsonObject parsing and does not want to build a third-party library into the compromise). An implementation under Gson is provided for reference only – gsonjsonAdapter.java

  • IRequestAdapter is responsible for requesting data. At present, wechat OAuth2 authorization and related requests for image download all use IRequestAdapter proxy, and URLConnection has been used to build an implementation. If you have your own requirements, you can rewrite this part. Note the compatibility of HTTPS requests, see -requestAdapterimp.java

The login function

Login function supports three platforms, QQ, wechat, Weibo;

// 3 platforms
Target.LOGIN_QQ;
Target.LOGIN_WX;
Target.LOGIN_WB;
Copy the code

Use OnLoginListener to listen to the return result of login. The returned LoginResult includes login type, basic user information, and token information.

public class LoginResult {
    // Login type, corresponding to target.login_qq etc...
    private int             type;
    // Basic user information returned
    // For the login type, you can forcibly change to WbUser,WxUser,QQUser to obtain richer information
    private BaseUser        mBaseUser;
    / / the token of the login information, openid, unionid, token, expires_in
    private BaseAccessToken mBaseToken;
}

// Log in result monitor
mOnLoginListener = new OnLoginListener() {
    @Override
    public void onLoginSucceed(LoginResult loginResult) {
        Log.e(TAG, loginResult.toString());
    }
    @Override
    public void onCancel(a) {
        toast("Login cancel");
    }
    @Override
    public void onException(PlatformException e) {
        toast("Login failed"+ e.toString()); }};// 3 platforms
Target.LOGIN_QQ;
Target.LOGIN_WX;
Target.LOGIN_WB;

// Wake up
LoginManager.login(mActivity, Target.LOGIN_QQ, mOnLoginListener);
Copy the code

Delete the authorization token. In order to avoid the bad experience of requiring users to open the authorization page and click authorization again every time they log in, the class library stores the token persistently. When the local token does not expire, the class library directly uses the token to request user information. It also provides a method to clear local tokens.

LoginManager.java

// Clear all platform tokens
public static void clearAllToken(Context context)
// Clear the token for the specified platform
public static void clearToken(Context context, @Target.LoginTarget int loginTarget)
Copy the code

sharing

Extension support

/ / text
ShareManager.sendSms(mActivity,"13612391817"."msg body");
/ / email
ShareManager.sendEmail(mActivity,"[email protected]"."subject"."msg body");
// Open channel corresponding application
ShareManager.openApp(mActivity,Target.SHARE_QQ_FRIENDS);
Copy the code

Eight kinds of data are supported

Share support for 8 types of data; If a platform is not compatible with certain types of sharing, web sharing will be used instead. For example, wechat does not support app sharing, so after sharing, the mode of web sharing is adopted. The eight supported types are as follows:

  1. Open the app for channel matching.
  2. Share text.
  3. Share images (JPG, PNG, GIF).
  4. Share the app.
  5. Share the web.
  6. Share the music.
  7. Share a video.
  8. Share a local video with an Intent.

8 sharing channels

// Supported sharing channels
Target.SHARE_DD; // Pin a friend
Target.SHARE_QQ_FRIENDS; / / qq friends
Target.SHARE_QQ_ZONE; / / qq space
Target.SHARE_WX_FRIENDS; // Wechat friends
Target.SHARE_WX_ZONE; // Wechat moments
Target.SHARE_WX_FAVORITE; // Wechat collection
Target.SHARE_WB_NORMAL; // Sina Weibo
Target.SHARE_WB_OPENAPI; // Sina Weibo openApi sharing. When you use this method to share pictures, there will be a small tail at the back of the microblog. You can click to enter the official microblog
Copy the code

Creating shared Data

When sharing, we first construct the data to share. The ShareObj object provides a variety of static methods to quickly create objects corresponding to the type of sharing.

// Test path
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/sSocialSdkConfig/2017-05-19/1495207225.mp3";
targetUrl = "http://bbs.csdn.net/topics/391545021";


// Open channel corresponding app
ShareObj shareMediaObj = ShareObj.buildOpenAppObj();
// Share text
ShareObj textObj = ShareObj.buildTextObj("Share text"."summary");
// Share images
ShareObj imageObj = ShareObj.buildImageObj("Share pictures"."summary", localImagePath);
/ / share GIF
ShareObj imageGifObj = ShareObj.buildImageObj("Share pictures"."summary", localGifPath);
Share the app / /
ShareObj appObj = ShareObj.buildAppObj("Share the app"."summary", localImagePath, targetUrl);
/ / share web
ShareObj webObj = ShareObj.buildWebObj("Share the web"."summary", localImagePath, targetUrl);
// Share video
ShareObj videoObj = ShareObj.buildVideoObj("Share video"."summary", localImagePath, targetUrl, localVideoPath, 10);
// Use an Intent to wake up a local video and support sharing with qq and wechat friends
ShareObj videoLocalObj = ShareObj.buildVideoObjByLocalPath(localVideoPath);
// Share music
ShareObj musicObj = ShareObj.buildMusicObj("Share music"."summary", localImagePath, targetUrl, netMusicPath, 10);
Copy the code

Share to monitor

Share the result, using OnShareListener for detection. OnShareListener provides a wealth of methods to support the various stages of sharing, as described in the next section.

public class SimpleShareListener implements OnShareListener{ @Override public void onStart(int shareTarget, ShareObj obj) {Override public ShareObj onPrepareInBackground(int shareTarget, ShareObj obj) { Return null if not requiredreturn null;
    }
    @Override
    public void onSuccess() {// Sharing succeeded} @override public void onFailure(SocialException e) {// Sharing failed} @override public void onFailureonCancel() {// Share cancel}}Copy the code

A share

// Wake up share
ShareManager.share(mActivity, Target.SHARE_QQ_FRIENDS, imageObj, mOnShareListener);
Copy the code

Overwrite the shared object

About rewriting the Shared object, before actually provide a can share to unify the need to share the ShareObj opportunities, among similar custom process, such as can be used to solve the network cannot share images, we need to download it to the local, for sharing, and such as image sharing watermark operations such as add app before you go out.

The onPrepareInBackground method of OnShareListener is overridden. This method will be executed before sharing. If not null is returned, the newly created ShareObj will be used for sharing. This method is executed on the child thread.

@Override
public ShareObj onPrepareInBackground(int shareTarget,ShareObj obj) {
    // Refactor the shared object, return null if not needed
    return null;
}
Copy the code

Take a look at a basic example, the main function is to download the network image to local before sharing and then update the image address pointed by ShareObj, so that the network image can be directly shared, of course, this function is built into the class library.

public class MyShareListener extends SimpleShareListener {

    public static final String TAG = MyShareListener.class.getSimpleName();

    private Context       mContext;
    private LoadingDialog mLoadingDialog;

    public MyShareListener(Context context) {
        mContext = context;
        mLoadingDialog = new LoadingDialog(mContext);
    }

    @Override
    public void onStart(int shareTarget, ShareObj obj) {
        if(mLoadingDialog ! =null)
            mLoadingDialog.show();
    }

    @Override
    public ShareObj onPrepareInBackground(int shareTarget, ShareObj obj) throws Exception{
        // Network path. Download files first
        ShareObjHelper.prepareThumbImagePath(obj);
        // Add watermark when sharing photos but not GIFs
        if(obj.getShareObjType() == ShareObj.SHARE_TYPE_IMAGE && ! FileHelper.isGifFile(obj.getThumbImagePath())) { File thumbImageFile =new File(obj.getThumbImagePath());
            File saveFile = new File(Constants.THUMB_IMAGE_PATH, thumbImageFile.getName());
            if(! FileUtil.fileIsExist(saveFile.getAbsolutePath())) { ImageUtils.drawWaterMarkSync(mContext, obj.getThumbImagePath(), saveFile.getAbsolutePath(),false.false);
            }
            obj.setThumbImagePath(saveFile.getAbsolutePath());
        }
        return obj;
    }

    @Override
    public void onSuccess(a) {
        ToastUtil.show("Share the success");
    }

    @Override
    public void onFailure(SocialException e) {
        switch (e.getErrorCode()) {
            case SocialException.CODE_NOT_INSTALL:
                ToastUtil.show("Application not installed");
                break;
        }
        L.e(TAG, "Share failure" + e.toString());
    }

    @Override
    public void onCancel(a) {
        ToastUtil.show("Share cancelled"); }}Copy the code