# Cocos2d-x SDK User Guide
TIP
Before accessing, please read the preparation before accessing .
You can get the Cocos2d-x SDK source code in GitHub (opens new window).
Cocos2d-x SDK supports running on iOS and Android platforms, and the size is about 6.8 M
**The latest version is: **v1. 2.0
**Updated: **202 2 - 01 - 04
Download address (opens new window)
# I. Initialize SDK
# 1.1 Integrated SDK
- Download the Cocos2d-x SDK (opens new window)resource file, extract the file, and put the ThinkingAnalytics folder into the Classes folder.
CMakeL ists.txt
Add the following configuration
list(APPEND GAME_SOURCE
Classes/ThinkingAnalytics/Common/TDJSONObject.cpp
)
list(APPEND GAME_HEADER
Classes/ThinkingAnalytics/Common/TDJSONObject.h
Classes/ThinkingAnalytics/Common/ThinkingAnalyticsAPI.h
)
if(ANDROID)
list(APPEND GAME_SOURCE
Classes/ThinkingAnalytics/Android/ThinkingAnalyticsAPI.cpp
)
To support Mac and Windows platforms, add the following configuration
elseif(WINDOWS)
list(APPEND GAME_HEADER
Classes/ThinkingAnalytics/Other/ThinkingSDKObject.h
)
list(APPEND GAME_SOURCE
Classes/ThinkingAnalytics/Other/ThinkingAnalyticsAPI.cpp
)
elseif(MACOSX)
list(APPEND GAME_HEADER
Classes/ThinkingAnalytics/Other/ThinkingSDKObject.h
)
list(APPEND GAME_SOURCE
Classes/ThinkingAnalytics/Other/ThinkingAnalyticsAPI.cpp
)
- Add Android configuration
- Add the libs folder under the app directory in the proj.android, put the thinkingsdk.aar into the libs folder
- Add the following configuration to the build.gradle in the app directory in the proj.android
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar','*.aar'])
}
- Add iOS configuration
Use XCode to open iOS project, drag and drop the iOS folder under ThinkingAnalytics directly into the Classes/ThinkingAnalytics directory
Build Setting- > Other Linker Flags
with Debug and Release added- all_load
Build Phases- > Compile Sources
in ThinkingA nalytics.mm Add-fobjc-arc
# 1.2 Initialize SDK
#include "./ThinkingAnalytics/Common/ThinkingAnalyticsAPI.h"
using namespace thinkingdata;
ThinkingAnalyticsAPI::init(TA_APP_ID, TA_SERVER_URL);
//Support for initializing multiple APPID instances
ThinkingAnalyticsAPI::init(TA_APP_ID_1, TA_SERVER_URL_1);
OR
// Get an example of TDConfig
Config config(TA_APP_ID, TA_SERVER_URL);
// Set Running Mode to Debug Mode
config.setModel(DEBUG);
// Initialize SDK
ThinkingAnalyticsAPI::init(config);
或者
Note: Since plaintext transmission is disabled by default on some devices, it is strongly recommended that you use the receiving end address in HTTPS format.
# II. Set User ID
After using the Cocos2d-x SDK, the SDK will use random UUID as the guest ID of each user by default, and this ID will be used as the user's identification ID in the unlogged state. It should be noted that the default guest ID will change when the user reinstates the game and changes the device.
# 2.1 Set Visitor ID (optional)
If your game has its own guest ID management system for each user, you can call identify
to set the guest ID:
ThinkingAnalyticsAPI::identify("cocos2dx_id");
If you need to get a guest ID, you can call getDistinctId
to get:
ThinkingAnalyticsAPI::getDistinctId();
# 2.2 Set and Clear Account ID
When the user logs in, you can call login
to set the user's account ID. After setting the account ID, the account ID will be used as the user identification ID, and the set account ID will be called logout
. Keep it until:
// Set account ID
ThinkingAnalyticsAPI::login("cocos2dx_user");
// Clear account ID
ThinkingAnalyticsAPI::logout();
Note: This method does not upload user login, user login and other events.
# III. Upload event
Through the ThinkingAnalytics API:: track ()
you can report events and their properties. In general, you may need to upload a dozen to hundreds of different events. If you are using TA background for the first time, we recommend that you upload a few key events first.
We also support several automatic collection events, including game startup, shutdown, installation and other events.
# 3.1 Upload Events
It is recommended that you set the properties of the event and the conditions for sending information according to the previously combed doc. Event type is a string
type that can only start with a letter and can contain numbers, letters and an underscore "_". It is up to 50 characters in length and is not sensitive to letter case.
TDJSONObject eventProperties;
eventProperties.setString("role", "warrior");
eventProperties.setNumber("coin",1);
ThinkingAnalyticsAPI::track("thinkingdata",eventProperties);
- The event attribute is of type
TDJSONObject
, where each element represents an attribute; - The event attribute
Key
is the attribute name and is ofstring
type. It can only start with letters, including numbers, letters and underscore "_". The maximum length is 50 characters and is not sensitive to letter case; - Property values support four types: string, numeric,
bool
, andList
types.
# 3.2 Set Static Public Properties
For some important attributes, such as the player's zone suit and channel, these attributes need to be set in each event. At this time, you can set these attributes as public event attributes. The public event property refers to the property that each event will carry. You can call setSuperProperties
to set the public event property. We recommend that you set the public event property before sending the event.
TDJSONObject userProperties;
userProperties.setString("level", "100");
userProperties.setDateTime("dateTime","2020-01-02 10:52:52.290");
ThinkingAnalyticsAPI::setSuperProperties(userProperties);
The public event properties will be saved to the cache and need not be called every time the app is started. If the call to setSuperProperties
uploads a previously set public event property, the previous property is overwritten. If the public event property and the Key
of a property uploaded by track ()
duplicate, the property of the event overrides the public event property.
If you need to delete a public event property, you can call unsetSuperProperty ()
to clear one of the public event properties; if you want to empty all public event properties, you can call clearSuperProperties ()
; if you want to get all public event properties, you can call getSuperProperties
;
// Clear the public property named channel
ThinkingAnalyticsAPI::unsetSuperProperty("CHANNEL");
// Clear all public properties
ThinkingAnalyticsAPI::clearSuperProperties();
// Get all public properties
ThinkingAnalyticsAPI::getSuperProperties();
# 3.3 Set Dynamic Public Properties
In v1.1.0, the feature of dynamic public attributes is added, that is, public attributes can obtain the current value when reporting, so that variable public attributes such as membership level can be easily reported. Once the dynamic public property class is set by setDynamicSuperProperties
, the SDK will automatically get the property when the event is reported and add it to the triggered event. The following example adds the time to the event every time the report is reported. When the event is triggered, the return value of the dynamicProperties
will be added to the event property.
// Get all public properties
TDJSONObject dynamicProperties()
{
TDJSONObject obj;
obj.setNumber("num",1);
return obj;
}
ThinkingAnalyticsAPI::setDynamicSuperProperties(dynamicProperties);
# 3.4 Record the Duration of the Event
If you need to record the duration of an event, you can call timeEvent ()
to start timing, configure the event type you want to time, and when you upload the event, you will automatically add #duration
to your event attribute to indicate the duration of the recording, in seconds.
// Call timeevent to turn on time_ Timing of event
ThinkingAnalyticsAPI::timeEvent("TIME_EVENT");
// do some thing...
// Upload time via track_ When the event event occurs, the #duration attribute is added to the attribute
ThinkingAnalyticsAPI::track("TIME_EVENT");
# IV. User Attribute
TA platform currently supports the user feature setting interface is user_set
, user_setOnce
,, user_add
, user_unset
, user_delete
, user_append
.
# 4.1 User_set
For general user feature, you can call user_set
to set it. Attributes uploaded using this interface will overwrite the original attribute value. If the user feature does not exist before, the user feature will be created.
TDJSONObject userProperties;
userProperties.setString("role", "warrior");
userProperties.setNumber("coin",1);
ThinkingAnalyticsAPI::user_set(userProperties);
Similar to event properties:
- Event attributes are of type
TDJSONObject
, where each element represents an attribute; - The event attribute
Key
is the attribute name, which is ofstring
type. It can only start with letters, including numbers, letters and underscore "_", with a maximum length of 50 characters, and is not sensitive to letter case; - Property values support four types: string, numeric,
bool
, andList
.
# 4.2 User_setOnce
If the user feature you want to upload only needs to be set once, you can call user_setOnce
to set it. When the attribute already has a value before, this information will be ignored:
TDJSONObject userProperties;
userProperties.setString("role", "warrior");
userProperties.setNumber("coin",1);
ThinkingAnalyticsAPI::user_setOnce(userProperties);
Note: The user feature type and restrictions set by the user_setOnce are consistent with user_set.
# 4.3 User_add
When you want to upload a numeric attribute, you can call user_add
to accumulate the attribute. If the attribute has not been set, a value of 0
will be assigned before calculation. Negative values can be passed in, which is equivalent to subtraction operations.
TDJSONObject userProperties;
userProperties.setNumber("coin",1);
ThinkingAnalyticsAPI::user_add(userProperties);
Note: The restrictions on attribute types and Key values in the user_add are consistent with user_set, but Value only allows numeric type attributes to be reported.
# 4.4 User_unset
If you need to reset a property of the user, you can call user_unset
to empty the value of the user feature specified by the user. This interface supports passing in parameters of string or list type:
ThinkingAnalyticsAPI::user_unset("coin");
# 4.5 User_delete
If you want to delete a user, you can call user_delete
to delete the user. You can no longer query the user feature of the user, but the events generated by the user can still be queried.
ThinkingAnalyticsAPI::user_delete();
# 4.6 User_append
You can call UserAppend
to append elements to a user feature of type List
:
TDJSONObject userProperties;
vector<string> listValue;
listValue.push_back("XX");
userProperties.setList("test",listValue);
ThinkingAnalyticsAPI::user_append(userProperties);
# V. Automatic Acquisition Events
The ThinkingAnalytics SDK provides automatic collection of three types of events:
- ta_app_install: The game is installed, when the game is opened for the first time after installation, the event will be collected
- ta_app_start: Collect the event when the game enters the foreground
- ta_app_end: Collect the event when the game retreats to the background
By calling the enableAutoTrack
interface, you can turn on automatic collection:
// Turn on automatic acquisition
ThinkingAnalyticsAPI::enableAutoTrack();
Note: If you need to customize the guest ID, be sure to call the Identify interface to set the guest ID before turning on the automatic collection function.
# VI. Other Configuration Options
# 6.1 Get the Device ID
After the SDK is initialized, the device ID will be automatically generated and recorded in the local cache. For the same application/game, the device ID of a device is unchanged. You can call getDeviceId ()
to obtain the device ID:
ThinkingAnalyticsAPI::getDeviceId();
// Use Device ID as Visitor ID
// ThinkingAnalyticsAPI::identify(ThinkingAnalyticsAPI::getDeviceId());
# 6.2 Print and Upload Data Log
ThinkingAnalyticsAPI::enableTrackLog(true);
# 6.3 Pause/stop data reporting
- Suspend SDK reporting (enableTracking)
You may want to temporarily stop SDK data collection and reporting in some scenarios, such as the user is in a test environment, or the user logged in to a test account. At this time, you can call the following interfaces to temporarily stop SDK reporting.
You can call enableTracking
through an instance (including the main instance and the light instance), pass in false
to suspend the reporting of the SDK, and the #distinct_id
, #account_id
, public attributes already set by the instance will be retained; the data that has been collected but has not been successfully reported by the instance will continue to try to report; the subsequent instance cannot collect and report any new data, cannot set visitor ID, account ID, and public attributes, etc., but can read the public attributes and Device ID, guest ID, account ID and other information.
The stop state of the instance will be saved in the local cache until enableTracking
is called and true
is passed in. The SDK instance will resume data collection and reporting. It should be noted that the light instance is not cached, so every time you open the APP, The paused state of the light instance will not be retained, and the reporting will be reopened.
// Pause reporting of default instances, cached data and information that has been set are not cleared
ThinkingAnalyticsAPI::enableTracking(false);
// Restore reporting of default instances
ThinkingAnalyticsAPI::enableTracking(true);
- Stop SDK reporting (optOutTracking)
In some special situations, you may need to completely stop the functions of the SDK. For example, in areas where GDPR is applicable, users choose not to provide data collection permissions, you can call the following interface to completely turn off the functions of the SDK.
OptOutTracking
can only be called through the main instance, and the biggest difference with enableTracking
is that it will empty the local cache of this instance, including the guest ID, account ID, public attributes, and unreported data queues of this instance. Then turn off the collection and reporting functions of this instance.
// Stop reporting default instances and empty local caches
ThinkingAnalyticsAPI::optOutTracking();
If you want to delete the user's user data in the TA cluster while turning off the SDK function, you can call optOutTrackingAndDeleteUser
, which will report a piece of user_delete
data before stopping the function of the SDK instance to delete the user's user data.
// Stop reporting the default instance and send user_ del
ThinkingAnalyticsAPI::optOutTrackingAndDeleteUser();
The stop state of the instance will also be saved in the local cache until optInTracking
is called, and subsequent reports can continue, but this is equivalent to a brand new instance
// Re-start reporting
ThinkingAnalyticsAPI::optInTracking();
# 6.4 SDK Operation Mode
The SDK supports running in three modes:
- NORMAL: Normal mode, data will be stored in the cache and reported according to a certain cache policy
- DEBUG: Debug mode, data is reported one by one. When problems occur, users will be prompted with logs and exceptions
- DEBUG_ONLY: Debug Only mode, only check the data, not into the library
Note: DEBUG mode is only used for integration phase data validation and should not be used in production mode.
In order to prevent Debug mode from going live in the production environment, it is stipulated that only specified devices can turn on Debug mode. Debug mode can only be enabled on the client side, and the device ID is configured in the 'Debug Data' section of the 'Event tracking management' page in the background of the TA.
The device ID can be obtained in three ways:
- #device_id attribute in event data in TA platform
- Client side log: The device DeviceId will be printed after the SDK initialization is completed
- Called through the instance interface: get device ID
# 6.5 Calibration Time
By default, the SDK uses the native time as the time of the event. If the user manually modifies the device time and affects your business analysis, you can use the current timestamp obtained from the server level to calibrate the SDK time. After that, all calls that do not specify a time, including event data and user feature setting operations, use the calibrated time as the time of occurrence.
// 1585633785954 is the current UNIX time stamp in milliseconds corresponding to Beijing Time 2020-03-31 13:49:45
ThinkingAnalyticsAPI::calibrateTime(1585633785954);
We also provide the ability to get time-to-SDK calibration from NTP. You need to pass in an NTP server address that your users can access. The SDK then tries to get the current time from the incoming NTP service address and calibrates the SDK time. If the correct return result is not obtained within the default timeout time (3 seconds), the data will be reported using the local time later.
// Time Calibration Using Apple NTP Service
ThinkingAnalyticsAPI::calibrateTimeWithNtp("time.apple.com");
Note:
- You need to choose your NTP server address carefully to ensure that the user equipment can get the server time quickly when the network is in good condition.
- There is some uncertainty in using the NTP service for time calibration. It is recommended that you give priority to using timestamp calibration.
# VII. Relevant Preset Attributes
# 7.1 Get preset properties
When server level event tracking requires some preset properties of the App side, you can obtain the preset properties of the App side through this method and then pass them to the server level.
//Get Attribute Object
PresetProperties* presetProperties = ThinkingAnalyticsAPI::getPresetProperties();
//Generate event preset properties
TDJSONObject* properties = presetProperties->toEventPresetProperties();
/*
{
"#carrier": "China Telecom",
"#os": "Android",
"#device_id": "abb8e87bfb5ce66c",
"#screen_height": 2264,
"#bundle_id": "com.sw.thinkingdatademo",
"#manufacturer": "realme",
"#device_model": "RMX1991",
"#screen_width": 1080,
"#system_language": "zh",
"#os_version": "10",
"#network_type": "WIFI",
"#zone_offset": 8
}
*/
//Get a preset property
string bundleId = presetProperties->bundleId;//name
string os = presetProperties->os;//os type,as Android
string systemLanguage = presetProperties->systemLanguage;//Cell phone system language type
int screenWidth = presetProperties->screenWidth;//Screen width
int screenHeight = presetProperties->screenHeight;//Screen height
string deviceModel = presetProperties->deviceModel;//Device Model
string deviceId = presetProperties->deviceId;//Unique Identification of Device
string carrier = presetProperties->carrier;//Mobile SIM Card Operator Information, Dual Card Dual Standby, Master Card Operator Information
string manufacture = presetProperties->manufacturer;//Mobile phone manufacturers such as HuaWei
string networkType = presetProperties->networkType;//Network Type
string osVersion = presetProperties->osVersion;//System Version Number
double zoneOffset = presetProperties->zoneOffset;//Time zone offset value
IP, country city information is generated by server level parsing, and the client side does not provide an interface to obtain these attributes
# VIII. Advanced Functions
The Cocos2d-x SDK supports reporting three special types of events: first-time events, updatable events, and rewritable events.
# 8.1 First Event
First-time events are events that are recorded only once for a device or another dimension ID. For example, in some scenarios, you may want to record the first event on a device, you can use first-time events to report data.
// Instance: Report device first event, assuming event name is DEVICE_ FIRST
TDJSONObject jsonObject;
jsonObject.setString("role","warrior");
TDFirstEvent *firstEvent = new TDFirstEvent("DEVICE_FIRST",jsonObject);
ThinkingAnalyticsAPI::track(firstEvent);
If you want to determine whether it is the first time in a dimension other than the device, you can set FIRST_CHECK_ID for the first event. For example, if you need to record the first event of an account, you can set the account ID to the FIRST_CHECK_ID of the first event:
// Instance: First event to report a user account, assuming the event name is USER_ FIRST
TDJSONObject jsonObject;
TDFirstEvent *firstEvent = new TDFirstEvent("USER_FIRST",jsonObject);
//firstEvent->setFirstCheckId("YOUR_ACCOUNT_ID");
ThinkingAnalyticsAPI::track(firstEvent);
Note: Due to the completion of the verification of whether it is the first time at the server level, the first event will be delayed by 1 hour by default.
# 8.2 Updatable Events
You can implement the need to modify event data in a specific scenario through updatable events. Updatable events need to specify an ID that identifies the event and pass it in when you create an updatable event object. The TA background will determine the data that needs to be updated based on the event name and event ID.
// Instance: Report an event that can be updated, assuming the event name is UPDATABLE_ EVENT
TDJSONObject jsonObject;
jsonObject.setNumber("status", 3);
jsonObject.setNumber("price", 100);
TDUpdatableEvent *updatableEvent = new TDUpdatableEvent("UPDATABLE_EVENT",jsonObject,"test_event_id");
// Event attributes after reporting are status 3 and price 100
ThinkingAnalyticsAPI::track(updatableEvent);
TDJSONObject jsonObject_new;
jsonObject_new.setNumber("status", 5);
// Event attributes status is updated to 5 after reporting, price remains unchanged
TDUpdatableEvent *updatableEvent = new TDUpdatableEvent("UPDATABLE_EVENT",jsonObject_new,"test_event_id");
ThinkingAnalyticsAPI::track(updatableEvent);
# 8.3 Rewritable Events
Rewritable events are similar to updatable events, except that rewritable events will completely cover historical data with the latest data, which is equivalent to deleting the previous data and storing the latest data in effect. The TA background will determine the data that needs to be updated based on the event name and event ID.
// Instance: Report an event that can be overridden, assuming the event name is OVERWRITABLE_ EVENT
TDJSONObject jsonObject;
jsonObject.setNumber("status", 3);
jsonObject.setNumber("price", 100);
TDOverWritableEvent *overWritableEvent = new TDOverWritableEvent("OVERWRITABLE_EVENT",jsonObject,"test_event_id");
ThinkingAnalyticsAPI::track(overWritableEvent);
TDJSONObject jsonObject_new;
jsonObject_new.setNumber("status", 5);
TDOverWritableEvent overWritableEvent_new = new TDOverWritableEvent("OVERWRITABLE_EVENT",jsonObject,"test_event_id");
// Event attributes status is updated to 5 and price attributes are deleted after reporting
ThinkingAnalyticsAPI::track(overWritableEvent_new);
# Release Note
# v1.2.0 2022/01/04
- Support for Mac and Windows data reporting
# v1.1.1 2021/11/19
- Support for custom instance names
- Support MacOS, Windows platform compilation
- Code optimization
- Update Android (2.7.3), iOS SDK (2.7.3)
# v1.1.0 2021/08/24
- Optimize initialization API
- Support dynamic public attributes
- Support multiple instances, light instances
- Support time calibration
# v1.0.1 2021/06/28
- Support prefabricated attribute acquisition
- Optimize support for Debug mode
# v1.0.0 2021/04/15
- Supports settings for Visitor ID and User Account
- Support event and user feature reporting
- Support automatic reporting of startup/shutdown/installation events
- Support public attribute interface
- Support timeEvent interface