Adding some social sharing functions to your mobile game will help promote the game and increase popularity. It is a good social marketing method. There are many third-party plug-ins in this area in China, such as ShareSDK, Aomeng Sharing Component, Baidu Sharing Component, etc. When studying version 2.2.2, the ShareSDK component was integrated. This time, when migrating to Cocos2d-x 3.0rc2, it still chose to integrate ShareSDK. Here we will talk about the integration process, some problems encountered and solutions. Here we only take Android platform game integration as an example.
1. Function description, SDK version and account preparation
The function is roughly as follows: set a button in the game, click this button, and the sharing icon set window of a well-known social platform pops up. After the user selects the sharing target, the relevant information will be shared to the corresponding social platform. Share results notifications are displayed at the bottom of the screen via Toast.
This time, we still use ShareSDK for Android 2.3.7 (ShareSDK-Android-2.3.7), and the Cocos2d-x version is 3.0rc2.
Before integration, you need to have a runnable Android platform game project based on Cocos2d-x 3.0rc2. Our integration is based on this project. Here our project is called GameDemo. The source code structure of GameDemo is roughly:
GameDemo/
– Classes/
– /
– Resources/
– cocos2d/
–
– … …
Before using ShareSDK, you need to apply for developer accounts and game access permissions (app_key, app_secret) on major mainstream social platforms (WeChat, Weibo). Of course, you should also have your own account and app AppKey on ShareSDK sites. The review of these applications will take several working days or even longer.
2. ShareSDK integration steps
According to the official manual of ShareSDK, there are three ways to integrate ShareSDK for Cocos2d-x. Previously, the method of dedicated component integration was adopted in the Cocos2d-x 2.2.2 engine. This component (C2DXShareSDKSample) can be downloaded here (/ShareSDKPlatform/C2DXShareSDKSample, which has recently fixed the bugs I found before).
Package integration
This time we mainly do social sharing on Weibo and WeChat, so we only need Weibo and WeChat related jar packages. Under C2DXShareSDKSample//libs, we find the following jar packages:
-rw-rw-r– 1 tonybai tonybai 97K April 8 18:10
-rw-rw-r– 1 tonybai tonybai 112K April 8 17:39 ShareSDK-Core-2.3.
-rw-rw-r– 1 tonybai tonybai 19K April 8 17:39 ShareSDK-SinaWeibo-2.3.
-rw-rw-r– 1 tonybai tonybai 4.3K April 8 17:39 ShareSDK-Wechat-2.3.
-rw-rw-r– 1 tonybai tonybai 29K April 8 17:39 ShareSDK-Wechat-Core-2.3.
-rw-rw-r– 1 tonybai tonybai 4.6K April 8 17:39 ShareSDK-Wechat-Favorite-2.3.
-rw-rw-r– 1 tonybai tonybai 4.4K April 8 17:39 ShareSDK-Wechat-Moments-2.3.
Copy these jar package files to GameDemo//libs.
2. Integrate configuration files and resource parts
Modify the GameDemo// file, and under the application tag, add the following Activity tag:
<activity
android:name=""
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait"
android:theme="@android:style/"
android:windowSoftInputMode="stateHidden|adjustResize" >
</activity>
<activity
android:name="."
android:configChanges="keyboardHidden|orientation|screenSize"
android:exported="true"
android:screenOrientation="portrait"
android:theme="@android:style/" />
Copy the files in the following directory under C2DXShareSDKSample//res to GameDemo//res:
drawable-hdpi/ drawable-ldpi/ drawable-mdpi/
drawable-xhdpi/ layout/ values/ values-en/
Note that you don’t copy files like this, just make your own judgment.
3. C++ part code integration
Copy the C2DXShareSDK folder under C2DXShareSDKSample/Classes to the GameDemo/Classes.
Since the class naming 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-x 3.0rc2 takes into account some compatibility issues, and most names are retained through the typedef defined in cocos2d/cocos/deprecated/, although these names have been suggested to be deprecated. In rc2, CCObject has been renamed Ref, which we need to manually modify in C2DXShareSDK.
In addition, when implementing the ShareSDK component, CCDictionary, CCArray and CCString, these three classes are deprecated in Cocos2d-x 3.0rc2, but we can still use them, so we can not make any modifications. But in the future, as the cocos2d-x version evolves, these classes are likely to be completely removed from the engine, and we need to re-use their alternatives for implementation.
In addition, we need to manually modify the getObjJson method in the C2DXShareSDK/Android/JSON/ file, because the real names of CCDictionary, CCString, and CCArray in rc2 have been replaced with __Dictionary, __String and __Array. CCDictionary, CCString, and CCArray are just typesedefs, so you need to make some modifications like the following (if you are integrating the cocos2d-x version, you do not need to make the following modifications):
cJSON * CCJSONConverter::getObjJson(Ref * obj)
{
std::string s = typeid(*obj).name();
if(("__Dictionary")!=std::string::npos){
cJSON * json = cJSON_CreateObject();
convertDictionaryToJson((CCDictionary *)obj, json);
return json;
}else if(("__Array")!=std::string::npos){
cJSON * json = cJSON_CreateArray();
convertArrayToJson((CCArray *)obj, json);
return json;
}else if(("__String")!=std::string::npos){
CCString * s = (CCString *)obj;
cJSON * json = cJSON_CreateString(s->getCString());
return json;
}else if(("CCNumber")!=std::string::npos){
CCNumber * n = (CCNumber *)obj;
cJSON * json = cJSON_CreateNumber(n->getDoubleValue());
return json;
}else if(("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 ShareSDK components themselves, and there is no need to modify them here.
Next we need to initialize the ShareSDK in:
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(""), "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);
}
Call the ShareSDK interface in the event callback function of the Share button for social platform sharing:
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 Sharing Test"), "title");
content->setObject(String::create(""), "titleUrl");
content->setObject(String::create(""), "url");
content->setObject(String::create("Tony Bai"), "site");
content->setObject(String::create(""), "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("Shared Success");
break;
case C2DXResponseStateFail:
app->showShareResultToast("Share failed");
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 = ->NewStringUTF(msg);
->CallStaticVoidMethod(, , jmsg);
if (->ExceptionOccurred()) {
->ExceptionDescribe();
->ExceptionClear();
return;
}
->DeleteLocalRef();
}
}
4. Java partial code integration
Create the cn/sharesdk path under GameDemo//src, and copy the onekeyshare and Copy under C2DXShareSDKSample //src/cn/sharesdk to the GameDemo//src/cn/sharesdk.
Copy ShareSDK-Android-2.3. The unzipped ShareSDK for Android/Src/wxapi to GameDemo//src//.
Modify GameDemo//src// file:
import ;
import ;
…
public class GameDemoActivity extends Cocos2dxActivity {
private static Context context;
private static Handler notifyHandler = new Handler() {
public void handleMessage(Message msg) {
switch () {
case 1:
String message = (String) ;
(context, message,
Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
context = this;
();
("YOUR_SHARESDK_APPKEY", true);
}
public static void showShareResultToast(String result) {
Message msg = new Message();
= 1;
= result;
(msg);
}
@Override
public void onDestroy() {
();
();
}
}
3. Problems and solutions
After modifying the above integration method, compile the app through cocos, run GameDemo in the simulator, click Share, and theoretically, the ShareSDK sharing window will appear at the bottom of the screen. Select the "Sina Weibo" icon, and the "Picture and Text Sharing" content window will be opened. Click "Share" in the upper right corner of the window.
[Question 1] The content of the "Picture Sharing" window is editable, and the soft keyboard always pops up, affecting the experience.
Expectation: The content cannot be edited, and the soft keyboard will not pop up by default.
Solution:
Open /src/cn/sharesdk/onekeyshare/ and make the following modifications:
Change the soft input method of the window by default to SOFT_INPUT_STATE_HIDDEN.
public void setActivity(Activity activity) {
(activity);
if (dialogMode) {
(.Theme_Dialog);
(Window.FEATURE_NO_TITLE);
}
().setSoftInputMode(
//.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
.SOFT_INPUT_STATE_HIDDEN);//default: hidden
}
Add a line to the initPageView: (null). Make the window content unmodified.
… …
// Text input area
etContent = new EditText(getContext());
( | );
(null);
((("text")));
(null);//make the edittext uneditable
(lpEt);
… …
}
[Question 2] Share to Weibo, click "Share", and the program will stop abnormally after a while.
Cause analysis:
Through debugging observation, it was found that ShareSDK had illegal memory access when parsing Json packages received from Weibo. The specific location is a problem that arises when parsing an array object. ShareSDK uses CCArray to store array objects in Json. The problem does not occur in cocos2d-x 2.2.2 version, but in cocos2d-x 3.0rc2 version. After comparing the code, it was found that the implementation of CCArray in the 3.0rc2 version is very different from the implementation of CCArray in the 2.2.2 version. It seems that it has undergone a large reconstruction. It is not yet certain whether it is a bug in the implementation of CCArray in the 3.0rc2 version.
Solution: Since the success of subsequent sharing results notification only depends on the status of the sharing, we only need to parse out the values of the three CCNumber type fields, "status", "action" and "platform". We do not need CCArray-type objects, so we just need to bypass the parsing and storing of Array-type fields and modify them as follows:
// Classes/C2DXShareSDK/Android/JSON/
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. Others
When using ShareSDK for social sharing, pay attention to the following two phenomena:
1) When you share on Weibo or WeChat for the first time, the authorization page will be opened, and the sharing will be successful after authorization;
2) The WeChat sharing window can only be opened when the mobile phone is connected to the Internet. If the mobile phone cannot be connected to the Internet, then WeChat friends, friends circle and collection sharing will not be able to open the sharing window, and there will be no prompts.