Integration and encapsulation of Android Social sharing

Sharing is one of the most frequent operations in APP. In the Android development environment, there are many third-party sharing frameworks. Popular ones include Aurora Social sharing (SharesDK), Ushare, Mob social sharing, and githut popular sharesDK, ShareUtil, BiliShare, ShareLoginLib, etc. Based on UmENG ShareSDK, this article introduces its integration process and modularizes its packaging for faster integration and use in projects.

Preparations for Integration

  1. Get umeng Appkey

    Register and add new apps on umeng + website to get Appkey. The application name on the Umeng background has nothing to do with the actual application name and package name. You are advised to name the application name + Platform (iOS/Android). The Android and iOS platforms cannot be shared and must be separated. You are advised to use an enterprise email address instead of an individual email address.

  2. Tripartite Account Application

    Because it involves interaction with various sharing platforms, applications need to be created on each platform and submitted for approval before integration. After the application is created, the icon and name of the application displayed during the sharing and login operations are related to the corresponding open platform Settings. The platforms for creating the application must be wechat, Sina, QQ, Facebook, Kakao, LinkeIn, Twitter and Dingding.

    Currently, the integrated content only includes wechat, Sina and QQ. The application channels are as follows:

    platform To apply for the address
    Wechat open platform open.weixin.qq.com/
    QQ Internet Platform connect.qq.com/
    Weibo open platform open.weibo.com

    Note 1: Application for QQ login must be made on QQ Internet platform, not on QQ open platform (open.qq.com).

    Note 2: Relevant qualifications of the enterprise may be required during the application process, such as corporate ID card, business license, tax registration certificate, etc., which should be prepared in advance.

    Note 3: When submitting an application, you need to submit the information related to the application (application name, introduction, icon, screenshot, authorization callback field, etc.), and wechat also needs to submit the wechat Open Platform Website Information Registration Form.

    Note 4: It is recommended that you apply for third-party open platforms with your corporate account instead of using your personal QQ, wechat, Weibo and email. In this way, you can avoid the risk of account management and the trouble of handover after the change of position or resignation of the applicant.

    Note 5: Most applications for open platform need to be reviewed. Therefore, at the beginning of the project, it is recommended to apply for an open platform account and create an application first, so as not to affect the development progress after a long application time.

    The application process is complicated, so you usually just look for product experience (# laughs). For practice, you can create a sample project using the official Demo package name com.umeng.soexample, using the signature file, Appkey, and the Appkey of each party.

Integrate umENG SDK

After modularization in the later stage, the packaged module can be integrated directly. Here I will first introduce the integration by adding SDK and the problems I have encountered.

  1. Download the SDK

    It can be seen from the latest SDK address that the sharing of Umeng includes many platforms. Here, we only use the sharing and login functions of Weibo, wechat and QQ, excluding payment, etc., so we can choose the three simplified versions downloaded by default. If necessary, you can refer to the official development documents to add use.

  2. Add the SDK

    Unzip the downloaded SDK package and use the contents in the common and Share folders. Copy all the other JAR files to your app/libs directory. Make sure you include implementation fileTree(include: implementation fileTree) in your gradle dependencies for your app. [‘*.jar’], dir: ‘libs’), import all jar packages from this folder into the project.

  3. Add a callback Activity

    Of the three platforms used, only wechat requires manual Activity addition. To do this, create a wxAPI folder in the package name directory and create an Activity named WXEntryActivity that inherits WXCallbackActivity with empty contents.

  4. Configure the Android Manifest XML

    Add each callback Activity to the Manifest of your project:

    <activity
        android:name=".wxapi.WXEntryActivity"
        android:configChanges="keyboardHidden|orientation|screenSize"
        android:exported="true"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" />
    <activity
        android:name="com.umeng.socialize.media.WBShareCallBackActivity"
        android:configChanges="keyboardHidden|orientation"
        android:exported="false"
        android:theme="@android:style/Theme.Translucent.NoTitleBar"></activity>
    <activity
        android:name="com.sina.weibo.sdk.web.WeiboSdkWebActivity"
        android:configChanges="keyboardHidden|orientation"
        android:exported="false"
        android:windowSoftInputMode="adjustResize"></activity>
    <activity
        android:name="com.sina.weibo.sdk.share.WbShareTransActivity"
        android:launchMode="singleTask"
        android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen">
        <intent-filter>
            <action android:name="com.sina.weibo.sdk.action.ACTION_SDK_REQ_ACTIVITY" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    
    </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="tencent100424468" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.tencent.connect.common.AssistActivity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" />
    Copy the code

    The APPkey of QQ needs to be replaced by the appkey I applied for. The official demo of Umeng is used here for testing.

  5. Add permissions

    Add the following permissions in AndroidManifest:

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    Copy the code

    If the targetSdkVersion of the project is higher than Android6.0, i.e. targetSdkVersion >= 23, you also need to add a dynamic request for permissions in the project:

    if (Build.VERSION.SDK_INT >= 23) {
        String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
        ActivityCompat.requestPermissions(this, mPermissionList, 123);
    }
    Copy the code
  6. Initialization Settings

    Now that we’ve integrated everything, we’re ready to start working at the code level. In the Application call umENG initialization interface, and set the appkey of each platform, here all use the official Demo test appkey.

    public class App extends Application {
        @Override
        public void onCreate(a) {
            super.onCreate();
            // Initialize the componentized base library. The statistical SDK/ push SDK/ share SDK must call this initialization interface
            UMConfigure.init(this."5bed13e1f1f5564655000404"."Umeng", UMConfigure.DEVICE_TYPE_PHONE,
                    "d9352161be267fb40fb12ad5eb04edf9");
            UMShareAPI.get(this);
        }
    
        // Platform configuration
        {
            / / WeChat
            PlatformConfig.setWeixin("wxdc1e388c3822c80b"."3baf1193c85774b3fd9d18447d76cab0");
            // Sina Weibo (the third parameter is the callback address)
            PlatformConfig.setSinaWeibo("3921700954"."04b48b094faeb16683c32669824ebdad"."http://sns.whalecloud.com");
            //QQ
            PlatformConfig.setQQZone("100424468"."c7394704798a158208a74ab60104f0ba");
            PlatformConfig.setYixin("yxc0614e80c9304c11b0391514d09f13bf");
            PlatformConfig.setTwitter("3aIN7fuF685MuZ7jtXkQxalyi"."MK6FEYG63eWcpDFgRYw4w9puJhzDl0tyuqWjZ3M7XJuuG7mMbO");
            PlatformConfig.setAlipay("2015111700822536");
            PlatformConfig.setLaiwang("laiwangd497e70d4"."d497e70d4c3e4efeab1381476bac4c5e");
            PlatformConfig.setPinterest("1439206");
            PlatformConfig.setKakao("e4f60e065048eb031e235c806b31c70f");
            PlatformConfig.setDing("dingoalmlnohc0wggfedpk");
            PlatformConfig.setVKontakte("5764965"."5My6SNliAaLxEm3Lyd9J");
            PlatformConfig.setDropbox("oz8v5apet3arcdy"."h7p2pjbzkkxt02a"); }}Copy the code
  7. Adding a Signature File

    Some platforms require the signature file of the project when applying for appKey, otherwise it will affect authorization. For a regular project, you just need to apply for a signature normally. Here’s how to add a signature as a test case.

    Copy the debug.keystore in the app directory of the official demo to your own practice project app directory

    Add the following code under the Android entry in your project’s app.gradle dependency:

    buildTypes {
        release {
            // Whether to obfuscate
            minifyEnabled false
            // Signature file
            signingConfig signingConfigs.debug
            // Obfuscate the location of the file
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            minifyEnabled false
            signingConfig signingConfigs.debug
            proguardFiles 'proguard-rules.pro'
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword "android"
            keyAlias "androiddebugkey"
            keyPassword "android"
        }
    }
    Copy the code

Start sharing

Finally, we come to the step of sharing. The mules or horses should be led out to see if they can walk. First, let’s introduce the two forms of Sharing by Umeng:

  • By using the sharing panel, users can call our method of opening the sharing panel and click the corresponding platform of the sharing panel to share.

  • For sharing without using the sharing panel, users can write the share button by themselves, or trigger the event, and then call our sharing method to share. In short, direct sharing is to insert sharing behavior into the user’s own interface component. The sharing panel is to open an interface component written by us and share according to click events.

    Shareable content includes:

platform authorization Shareable content The user information
qq is Text picture link video music is
Qq space With qq Text (say) picture (say) link video music With qq
WeChat is Text picture link video music is
Wechat moments With WeChat Text image link video music (share link does not show description) With WeChat
WeChat collection With WeChat Text picture link video music file With WeChat
Sina weibo is Text picture link video music file is

The following to directly share a website to the wechat platform as an example, look at the specific code implementation:

  UMWeb web = new UMWeb("https://gank.io/");// Create a Web object to share, passing in the URL to share
  web.setTitle("Test sharing title");// Set the title
  web.setThumb(new UMImage(this, R.drawable.thumb));// Set the thumbnail that is passed in for display
  web.setDescription("Test Share Content Test Share Content Test Share Content Test Share Content Test Share Content");// Set description
  new ShareAction(ShareDetailActivity.this)// Enable sharing
                  .withMedia(web) // Fill in the created share content
                  .setPlatform(SHARE_MEDIA.WEIXIN)// Select share platform
                  .setCallback(shareListener)// Set the listening for the share returns
                  .share();// Start the sharing operation
Copy the code

The implementation effect is as follows:

Share this site as a panel:

  ShareBoardlistener boardListener = new ShareBoardlistener() { // Create a listener for the panel
      @Override
      public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA platform) {
          new ShareAction(mActivity)// Enable sharing
                  .withMedia(web) // Fill in the created share content
                  .setPlatform(platform)// Fill in the selected platform
                  .setCallback(shareListener)// Set the listening for the share returns
                  .share();// Start the sharing operation}};new ShareAction(mActivity)
          .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.WEIXIN_FAVORITE,
                  SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE)// Set the platform to display the share panel
          .setShareboardclickCallback(boardListener)// Add the panel listener you created earlier
          .open(config);// Open the share panel in which you can pass in a Config object that can customize the panel style
  		// Set whether the panel should be displayed at the bottom or in the middle, whether there is a cancel button, icon shape, font size, background color, etc
Copy the code

The default centered panel looks like this:

Finally, don’t forget to add the following code to your shared Activity to turn off listening and prevent memory leaks.

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
  }
  @Override
      protected void onDestroy(a) {
          super.onDestroy();
          UMShareAPI.get(this).release();
      }
Copy the code

Modular and code encapsulation for UmENG sharing

In the previous content, we completely experienced the preparation, integration and use of UmENG social sharing. Although it seems simple and clear, it is still easy for people to encounter problems for the first time, and the multiple integration in the project is also tedious. Therefore, the focus of this paper is to carry out modularization for the sharing of UmENG, import modules directly when needed, and encapsulate the main methods to improve efficiency and reduce the amount of code during development.

The following records the ideas and processes in the encapsulation process, as well as the use method after encapsulation.

  • Encapsulation process

    In the previous usage introduction, we can see that each share needs to create the content to be shared in advance. The more data that needs to be passed in, the more lines of code, so the created object should be encapsulated first.

    According to the type of sharing, there are eight categories:

    Sharing type Enumeration parameter
    Only text SHARE_TYPE_TEXT
    Only pictures SHARE_TYPE_IMAGE
    graphic SHARE_TYPE_TEXTANDIMG
    The url SHARE_TYPE_WEB
    Network video SHARE_TYPE_VIDEO
    Online music SHARE_TYPE_MUSIC
    GIF expression SHARE_TYPE_EMOJI
    Wechat applets SHARE_TYPE_MINAPP

    Images can be created by resource File ID, File File, network address, Bitmap object, and Byte []. Although many other types do not need images, many need thumbnails, and thumbnails are pictures in nature, so thumbnails can be isolated:

    private static UMImage mThumb;
    // Create thumbnails to share
    public static void createThumbImage(int thumbResId) {
        mThumb = new UMImage(mActivity, thumbResId);
    }
    
    public static void createThumbImage(File thumbFile) {
        mThumb = new UMImage(mActivity, thumbFile);
    }
    
    public static void createThumbImage(String thumbImageUrl) {
        mThumb = new UMImage(mActivity, thumbImageUrl);
    }
    
    public static void createThumbImage(Bitmap thumbBitmap) {
        mThumb = new UMImage(mActivity, thumbBitmap);
    }
    
    public static void createThumbImage(byte[] thumbBytes) {
        mThumb = new UMImage(mActivity, thumbBytes);
    }
    Copy the code

    The first three are strings. The most complex thumbnails have already been created using the above method, so just add the first three contents:

    private static UMWeb mWeb;
    // Thumbnails are required to create links to share
    public static void createUrl(String url, String title, String description) {
        mWeb = new UMWeb(url);
        mWeb.setTitle(title);
        mWeb.setDescription(description);
        mWeb.setThumb(mThumb);// Pass in the created thumbnail
    }
    Copy the code

    Now that we’ve created the url object to share, sharing is the natural next step. The implementation is very simple and crude, passing in the enumeration name for the platform and type to be shared:

    public static void share(SHARE_MEDIA platform, SHARE_TYPE shareType) {
        ShareAction action = new ShareAction(mActivity)
                .setPlatform(platform).setCallback(mListener);
        switch (shareType) {
            case SHARE_TYPE_TEXT:
                action.withText(mText).share();
                break;
            case SHARE_TYPE_IMAGE:
                action.withMedia(mImage).share();
                break;
            case SHARE_TYPE_TEXTANDIMG:
                action.withText(mText).withMedia(mImage).share();
                break;
            case SHARE_TYPE_WEB:
                action.withMedia(mWeb).share();
                break;
            case SHARE_TYPE_VIDEO:
                action.withMedia(mVideo).share();
                break;
            case SHARE_TYPE_MUSIC:
                action.withMedia(mMusic).share();
                break;
            case SHARE_TYPE_EMOJI:
                action.withMedia(mEmoji).share();
                break;
            case SHARE_TYPE_MINAPP:
                action.withMedia(mMinAPP).share();
                break; }}Copy the code

    So what if the user doesn’t need the share callback we’ve already set up and wants to customize it? So we need to build a method for the user to pass in a custom listener:

    // Set the custom listening mode for sharing listener incoming
    public static void setShareListener(UMShareListener listener) {
        mListener = listener;
    }
    Copy the code

    In addition to direct sharing, there is sharing in the form of panels, where three forms of encapsulation are provided:

    1. Display the share panel directly in the middle

      public static void shareBoardAtCenter(SHARE_TYPE shareType) {
          ShareBoardConfig config = new ShareBoardConfig();
          config.setShareboardPostion(ShareBoardConfig.SHAREBOARD_POSITION_CENTER);
          config.setCancelButtonVisibility(true);
          shareBoard(config, shareType);
      }
      Copy the code
    2. The share panel is displayed at the bottom

      public static void shareBoardAtBottom(SHARE_TYPE shareType) {
          ShareBoardConfig config = new ShareBoardConfig();
          config.setShareboardPostion(ShareBoardConfig.SHAREBOARD_POSITION_BOTTOM);
          config.setCancelButtonVisibility(true);
          shareBoard(config, shareType);
      }
      Copy the code
    3. User – defined sharing panel

      public static void setBoardWithConfig(ShareBoardConfig config, SHARE_TYPE shareType) {
          shareBoard(config, shareType);
      }
      Copy the code

    ShareBoard (); shareBoard(); shareBoard(); shareBoard()

    private static void shareBoard(ShareBoardConfig config, final SHARE_TYPE shareType) {
        ShareBoardlistener boardListener = new ShareBoardlistener() {
            @Override
            public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA platform) { share(platform, shareType); }};new ShareAction(mActivity)
                .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.WEIXIN_FAVORITE,
                        SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE)
                .setShareboardclickCallback(boardListener)
                .open(config);
    }
    Copy the code

    SetPlatforms (); setPlatforms(); setPlatforms();

    // Set the content to be shared in the share panel
    public static void setBoardPlatforms(SHARE_MEDIA[] platforms) {
        mPlatforms = platforms;
    }
    Copy the code
  • Method of use

    The overall usage is relatively straightforward, but it should be noted that, except for sharing text images, remember to create thumbnails first.

    Here’s an example of sharing a website or video:

    // We need to initialize it first
    UShareUtils.init(this);
    // Create thumbnails
    UShareUtils.createThumbImage(R.drawable.cat80);
    // Create a url to share, passing in the url, title, and description
    UShareUtils.createUrl("https://gank.io/"."Share title"."Share description");
    // Create a video to share, passing in the video address, title, and description
    UShareUtils.createVideo("http://vfx.mtime.cn/Video/2018/10/26/mp4/181026140242572417.mp4"."How to Train Your Dragon 3".How to Train Your Dragon 3 is the highly anticipated third installment in dreamWorks Animation's one of the most popular animated series in history. ");
    // Click Share
    @OnClick({R.id.tv_share_web, R.id.tv_share_video, R.id.tv_share_board, R.id.tv_share_center})
      	public void onViewClicked(View view) {
                switch (view.getId()) {
                    case R.id.tv_share_web:
                        // Share WEB to QQ
                        UShareUtils.share(SHARE_MEDIA.QQ, SHARE_TYPE.SHARE_TYPE_WEB);
                        break;
                    case R.id.tv_share_video:
                        // Share video to wechat
                        UShareUtils.share(SHARE_MEDIA.WEIXIN, SHARE_TYPE.SHARE_TYPE_VIDEO);
                        break;
        		   case R.id.tv_board_board:
                        // Open the bottom sharing panel to share the WEB
                        UShareUtils.shareBoardAtBottom(SHARE_TYPE.SHARE_TYPE_WEB);
                        break;
                    case R.id.tv_board_center:
                        // Open the middle share panel to share the video
                        UShareUtils.shareBoardAtBottom(SHARE_TYPE.SHARE_TYPE_VIDEO);
                        break; }}Copy the code