Detailed steps and faqs for integrated social sharing ShareSDK in Cocos2d x 3.0

  • 2020-05-30 21:03:34
  • OfStack

Add some social sharing functions to your mobile games, which can help promote the game and improve its popularity. It is a good means of social marketing. In China, there are quite a few third party plug-ins in this aspect, such as ShareSDK, friends' alliance sharing component, Baidu sharing component, etc. When we studied version 2.2.2 before, we integrated ShareSDK. This time, we still chose to integrate ShareSDK when we migrated to Cocos2d-x 3.0 rc2. This is just an example of game integration on the Android platform.


1. Function description, SDK version and account preparation

The function is roughly like this: set a button in the game, click the button, pop up the sharing icon set window of the well-known social platform, after the user selects the sharing target, the relevant information will be Shared to the corresponding social platform. The share result notification is displayed at the bottom of the screen via Toast.

This time, ShareSDK for Android version 2.3.7 (ShareSDK-Android-2.3.7) will still be used, while Cocos2d-x version 3.0rc2 will be used.

Before integration, you need to have a working Android platform game project based on Cocos2d-x 3.0rc2. Our integration is based on project. Here, our project is called GameDemo, and the source structure of GameDemo is roughly:


GameDemo/
     �  Classes/
     �  proj.android/
     �  Resources/
     �  cocos2d/
     �  CMakeLists.txt
     �   ...   ... 

Before using ShareSDK, you need to apply for developer accounts and game access rights (app_key, app_secret) on major social media platforms (WeChat, weibo). Of course, you should also have your own account and application AppKey on ShareSDK site. The review of these applications will take several working days or even longer.

2. Integration steps of ShareSDK

According to official ShareSDK manual Cocos2d - x integrated ShareSDK there are three kinds of ways, before Cocos2d - x 2.2.2 engine USES a special way of component integration, the component (C2DXShareSDKSample) can be downloaded here (https: / / github com/ShareSDKPlatform/C2DXShareSDKSample, the component has been fix before I recently discovered bug).

1. jar package integration

This time we mainly do social sharing on weibo and WeChat, so we only need the jar package related to weibo and WeChat. In C2DXShareSDKSample/proj android/libs, we find the following jar package:


  -rw-rw-r �  1 tonybai tonybai  97K  4 month   8 18:10 mframework.jar
  -rw-rw-r �  1 tonybai tonybai 112K  4 month   8 17:39 ShareSDK-Core-2.3.7.jar
  -rw-rw-r �  1 tonybai tonybai  19K  4 month   8 17:39 ShareSDK-SinaWeibo-2.3.7.jar
  -rw-rw-r �  1 tonybai tonybai 4.3K  4 month   8 17:39 ShareSDK-Wechat-2.3.7.jar
  -rw-rw-r �  1 tonybai tonybai  29K  4 month   8 17:39 ShareSDK-Wechat-Core-2.3.7.jar
  -rw-rw-r �  1 tonybai tonybai 4.6K  4 month   8 17:39 ShareSDK-Wechat-Favorite-2.3.7.jar
  -rw-rw-r �  1 tonybai tonybai 4.4K  4 month   8 17:39 ShareSDK-Wechat-Moments-2.3.7.jar

These jar Copy package file to GameDemo/proj android/libs.

2. Integration of configuration files and resources

Modify GameDemo/proj. android/AndroidManifest. xml file, under application tags, add the following Activity tags:


        <activity
            android:name="cn.sharesdk.framework.ShareSDKUIShell"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:windowSoftInputMode="stateHidden|adjustResize" >
    </activity>
    <activity
            android:name=".wxapi.WXEntryActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:exported="true"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

Will C2DXShareSDKSample/proj android/res under the following directory file is copied to the GameDemo/proj android/res under:


   drawable-hdpi/  drawable-ldpi/  drawable-mdpi/ 
   drawable-xhdpi/  layout/  values/  values-en/

Note: don't copy files like icon.png.

3. C++ partial code integration

Put C2DXShareSDKSample/Classes under C2DXShareSDK folder Copy under GameDemo/Classes.

Since the class name of Cocos2d-x 3.0rc2 has changed, we need to modify the class name and method name in the engine used in C2DXShareSDK. But in fact Cocos2d - 3.0 rc2 x considered 1 some compatibility problems, most of the name by cocos2d cocos/deprecated/CCDeprecated h defined typedef preserved, although these names have been advised to deprecated. In rc2, CCObject has been renamed Ref, which we need to modify manually in C2DXShareSDK.

In addition, ShareSDK components make extensive use of CCDictionary, CCArray and CCString in the implementation, and these three classes are all used by deprecated in Cocos2d-x 3.0rc2, but we can still use them, so we can not modify them. However, with the evolution of the cocos2d-x version, it is likely that these classes will be removed from the engine completely and we will need to re-implement them using their substitutes.

In addition we also need to manually modify the C2DXShareSDK under 1 / Android JSON/CCJSONConverter cpp file getObjJson method, because the rc2 CCDictionary, CCString, CCArray true name has been replaced by these classes __Dictionary, __String and __Array CCDictionary, CCString, CCArray just some typedef, So make the following changes (if you are integrating the cocos2d-x 2.x.x version, you do not need to make the following changes) :


cJSON * CCJSONConverter::getObjJson(Ref * obj)
{
    std::string s = typeid(*obj).name();
    if(s.find("__Dictionary")!=std::string::npos){
        cJSON * json = cJSON_CreateObject();
        convertDictionaryToJson((CCDictionary *)obj, json);
        return json;
    }else if(s.find("__Array")!=std::string::npos){
        cJSON * json = cJSON_CreateArray();
        convertArrayToJson((CCArray *)obj, json);
        return json;
    }else if(s.find("__String")!=std::string::npos){
        CCString * s = (CCString *)obj;
        cJSON * json = cJSON_CreateString(s->getCString());
        return json;
    }else if(s.find("CCNumber")!=std::string::npos){
        CCNumber * n = (CCNumber *)obj;
        cJSON * json = cJSON_CreateNumber(n->getDoubleValue());
        return json;
    }else if(s.find("CCNull")!=std::string::npos){
        cJSON * json = cJSON_CreateNull();
        return json;
    }
    CCLog("CCJSONConverter encountered an unrecognized type");
    return NULL;
}

CCNumber and CCNull are the class names implemented by the ShareSDK component itself and need not be modified here.

Next, we need to initialize ShareSDK in AppDelegate.cpp:


bool AppDelegate::applicationDidFinishLaunching() {
     ...   ... 
    initShareSDK();
     ...  ..
}
void AppDelegate::initShareSDK()
{
    // sina weibo
    CCDictionary *sinaConfigDict = CCDictionary::create();
    sinaConfigDict->setObject(CCString::create("YOUR_WEIBO_APPKEY"), "app_key");
    sinaConfigDict->setObject(CCString::create("YOUR_WEBIO_APPSECRET"), "app_secret");
    sinaConfigDict->setObject(CCString::create("http://www.sharesdk.cn"), "redirect_uri");
    C2DXShareSDK::setPlatformConfig(C2DXPlatTypeSinaWeibo, sinaConfigDict);
    // wechat
    CCDictionary *wcConfigDict = CCDictionary::create();
    wcConfigDict->setObject(CCString::create("YOUR_WECHAT_APPID"), "app_id");
    C2DXShareSDK::setPlatformConfig(C2DXPlatTypeWeixiSession, wcConfigDict);
    C2DXShareSDK::setPlatformConfig(C2DXPlatTypeWeixiTimeline, wcConfigDict);
    C2DXShareSDK::setPlatformConfig(C2DXPlatTypeWeixiFav, wcConfigDict);
    C2DXShareSDK::open(CCString::create("YOUR_SHARESDK_APPKEY"), false);
}

The ShareSDK interface is called in the event callback function of the Share button to share on the social platform:


void GameScene::menuShareCallback(Ref* sender)
{
    Dictionary *content = Dictionary::create();
    content->setObject(String::create("ShareSDK for Cocos2d-x 3.0rc2 Social sharing test. ")
                        , "content");
    content->setObject(String::create("ShareSDK Share the testing "), "title");
    content->setObject(String::create("http://tonybai.com"), "titleUrl");
    content->setObject(String::create("http://tonybai.com"), "url");
    content->setObject(String::create("Tony Bai"), "site");
    content->setObject(String::create("http://tonybai.com"), "siteUrl");
    content->setObject(String::createWithFormat("%s", YOUR_LOCAL_IMAGE_PATH)
                       , "image");
    content->setObject(String::createWithFormat("%d", C2DXContentTypeNews)
                       , "type");
    C2DXShareSDK::showShareMenu(NULL, content, CCPointMake(100, 100),
                          C2DXMenuArrowDirectionLeft, shareResultHandler);
}
void shareResultHandler(C2DXResponseState state,
                        C2DXPlatType platType,
                        Dictionary *shareInfo,
                        Dictionary *error)
{
    AppDelegate *app = (AppDelegate*)Application::getInstance();
    switch (state) {
        case C2DXResponseStateSuccess:
            CCLog("Share Ok");
            app->showShareResultToast(" Share success ");
            break;
        case C2DXResponseStateFail:
            app->showShareResultToast(" Share the failure ");
            CCLog("Share Failed");
            break;
        default:
            break;
    }
}

showShareResultToast is implemented as follows:


void AppDelegate::showShareResultToast(const char *msg)
{
    JniMethodInfo t;
    if (JniHelper::getStaticMethodInfo(t, "YOUR_ACTIVITY_NAME",
        "showShareResultToast", "(Ljava/lang/String;)V")) {
        jstring jmsg = t.env->NewStringUTF(msg);
        t.env->CallStaticVoidMethod(t.classID, t.methodID, jmsg);
        if (t.env->ExceptionOccurred()) {
            t.env->ExceptionDescribe();
            t.env->ExceptionClear();
            return;
        }
        t.env->DeleteLocalRef(t.classID);
    }
}

4. Java partial code integration

In GameDemo/proj android/src establish cn/sharesdk path below, will C2DXShareSDKSample/proj android/src/cn/sharesdk onekeyshare under and ShareSDKUtils java Copy to GameDemo/proj android/src/cn/sharesdk below.

Will ShareSDK - Android - 2.3.7. zip decompression after ShareSDK for Android Src/wxapi Copy to GameDemo/proj android/src/com tonybai. game/under.

Modify GameDemo/proj android/src/com tonybai. game/GameDemoActivity java file:


import android.widget.Toast;
import cn.sharesdk.ShareSDKUtils;
 ... 
public class GameDemoActivity extends Cocos2dxActivity {
    private static Context context;
    private static Handler notifyHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String message = (String) msg.obj;
                    Toast.makeText(context, message,
                      Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        ShareSDKUtils.prepare();
        ShareSDKUtils.initSDK("YOUR_SHARESDK_APPKEY", true);
    }
    public static void showShareResultToast(String result) {
        Message msg = new Message();
        msg.what = 1;
        msg.obj = result;
        notifyHandler.sendMessage(msg);
    }
    @Override
    public void onDestroy() {
        ShareSDKUtils.stopSDK();
        super.onDestroy();
    }
}

3. Problems and solutions

After the above integration method is modified, compile app via cocos, run GameDemo in the simulator, and click Share. In theory, the ShareSDK share window will appear at the bottom of the screen. Select the "sina weibo" icon, and the "graphic share" content window will be opened.

[question 1] the content of the "picture and text sharing" window can be edited, and the soft keyboard always pops up, affecting the experience.

Expectation: the content is not editable, no soft keyboard pops up by default
Solutions:
Open proj. android src/cn sharesdk/onekeyshare/EditPage java, make the following changes:

Change the soft input mode of the window to SOFT_INPUT_STATE_HIDDEN by default.


      public void setActivity(Activity activity) {
        super.setActivity(activity);
        if (dialogMode) {
            activity.setTheme(android.R.style.Theme_Dialog);
            activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        activity.getWindow().setSoftInputMode(
                   //WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                   WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);//default: hidden
    }

Add 1 line to initPageView: etContent.setKeyListener (null). Make window contents unmodifiable.

  -rw-rw-r �  1 tonybai tonybai  97K  4 month   8 18:10 mframework.jar
  -rw-rw-r �  1 tonybai tonybai 112K  4 month   8 17:39 ShareSDK-Core-2.3.7.jar
  -rw-rw-r �  1 tonybai tonybai  19K  4 month   8 17:39 ShareSDK-SinaWeibo-2.3.7.jar
  -rw-rw-r �  1 tonybai tonybai 4.3K  4 month   8 17:39 ShareSDK-Wechat-2.3.7.jar
  -rw-rw-r �  1 tonybai tonybai  29K  4 month   8 17:39 ShareSDK-Wechat-Core-2.3.7.jar
  -rw-rw-r �  1 tonybai tonybai 4.6K  4 month   8 17:39 ShareSDK-Wechat-Favorite-2.3.7.jar
  -rw-rw-r �  1 tonybai tonybai 4.4K  4 month   8 17:39 ShareSDK-Wechat-Moments-2.3.7.jar
0
[question 2] share to weibo. After clicking "share", the program will stop abnormally after 1.

Reason analysis:
Through debugging observation, it was found that ShareSDK was experiencing illegal memory access while parsing the Json package received from Weibo. The location is a problem when parsing an array object. CCArray USES CCArray to store array objects in Json. This problem does not appear in cocos2d-x 2.2.2, but it does appear in cocos2d-x 3.0rc2. The code comparison shows that the implementation of CCArray in version 3.0rc2 is quite different from that in version 2.2.2 CCArray, which seems to be a big refactoring. It is not clear whether it is bug implemented in version 3.0rc2.

Solution: since the subsequent notification of sharing results only depends on the status of sharing, we only need to parse out the values of the three CCNumber type fields: "status", "action" and "platform". We don't need objects of type CCArray, so we just need to bypass the parsing and storage of type Array fields, as follows:


// Classes/C2DXShareSDK/Android/JSON/CCJSONConverter.cpp
void CCJSONConverter::convertJsonToDictionary(cJSON *json, CCDictionary *dictionary)
{
    dictionary->removeAllObjects();
    cJSON * j = json->child;
    while (j) {
        if (j->type == cJSON_Number) {
            Ref * obj = getJsonObj(j);
            dictionary->setObject(obj, j->string);
        }
        j = j->next;
    }
}

4. Other

When using ShareSDK for social sharing, notice the following two phenomena:
1) when sharing on weibo or WeChat for the first time, the authorization page will be opened. Only after authorization can the sharing be successful;
2) the WeChat sharing window can only be opened when the phone is connected to the Internet. If the phone is not connected to the Internet, WeChat friends, circles of friends and favorite share will not be able to open the share window and there will be no prompt.


Related articles: