Advanced guide
1. Set user IDs
By default, the SDK instance uses a random UUID as each user's default distinct ID, which serves as the user's identifier when they are not logged in. Note that the distinct ID changes when the user reinstalls the app or switches devices.
1.1 Set the distinct ID
In general, you don't need to customize the distinct ID. Make sure you understand the user identification rules before you set a distinct ID.
If you need to replace the distinct ID, call the method immediately after the SDK is initialized. Do not call it multiple times, to avoid creating useless accounts.
If your app has its own distinct ID management system for each user, you can call setDistinctId to set the distinct ID:
// Set the distinct ID to Thinker
TDAnalytics.setDistinctId("Thinker");
To get the current distinct ID, call getDistinctId:
//Return the distinct ID
let distinctId = TDAnalytics.getDistinctId();
1.2 Set the account ID
When a user logs in, you can call login to set the user's account ID. The AE platform uses the account ID as the identifier, and the account ID you set is kept until logout is called. Calling login multiple times overwrites the previous account ID.
//The unique login identifier of the user, which corresponds to #account_id in the reported data. In this case, the value of #account_id is TA
TDAnalytics.login("TA");
This method does not upload a login event
1.3 Clear the account ID
After a user logs out, you can call logout to clear the account ID. Until login is called again, the distinct ID is used as the identifier.
// Remove "#account_id" from the reported data. Subsequent data will not carry "#account_id"
TDAnalytics.logout();
We recommend calling logout only on explicit logout events, for example when the user deletes their account, rather than when the app is closed.
This method does not upload a logout event
2. Track events
After the SDK is initialized, you can start tracking data to collect user behavior. In most cases, regular events meet business needs. You can also use first events, updatable events, and other event types based on your actual business scenarios.
2.1 Regular events
You can call track to upload events. We recommend setting event properties according to the tracking plan you prepared earlier. The following example tracks a user purchasing a product:
TDAnalytics.track({
eventName: "product_buy", // Event name
properties: {
product_name: "Product Name"
} //Event properties
});
2.2 First events
A first event is an event that is recorded only once for a given device or an ID of another dimension. For example, in some scenarios you may want to record the activation event on a device; you can report this data as a first event.
TDAnalytics.trackFirst({
eventName: "device_activation",
properties: { key: "value" }
});
If you want to determine whether an event is the first one based on a dimension other than the device, you can customize first_check_id for the first event:
// Set the user ID as the first_check_id of the first event to track first-time user activation
TDAnalytics.trackFirst({
eventName: "account_activation",
firstCheckId: "TA",
properties: { key: "value" }
});
Note: Because the first-event check is performed on the server, first events are stored with a 1-hour delay by default.
2.3 Updatable events
You can use updatable events when you need to modify event data in specific scenarios. An updatable event requires an ID that identifies the event, which you pass in when creating the updatable event object. AE determines which data to update based on the event name and event ID.
// Example: report an updatable event, assuming the event name is UPDATABLE_EVENT
// After reporting, the event property status is 3 and price is 100
TDAnalytics.trackUpdate({
eventName: "UPDATABLE_EVENT",
properties: { status: 3, price: 100 },
eventId: "test_event_id"
});
// After reporting, the event property status is updated to 5 and price is unchanged
TDAnalytics.trackUpdate({
eventName: "UPDATABLE_EVENT",
properties: { status: 5 },
eventId: "test_event_id"
});
2.4 Overwritable events
Overwritable events are similar to updatable events, except that an overwritable event completely overwrites the historical data with the latest data. In effect, this is equivalent to deleting the previous record and storing the latest one. AE determines which data to update based on the event name and event ID.
// Example: report an overwritable event, assuming the event name is OVERWRITE_EVENT
// After reporting, the event property status is 3 and price is 100
TDAnalytics.trackOverwrite({
eventName: "OVERWRITE_EVENT",
properties: { status: 3, price: 100 },
eventId: "test_event_id"
});
// After reporting, the event property status is updated to 5 and the price property is deleted
TDAnalytics.trackOverwrite({
eventName: "OVERWRITE_EVENT",
properties: { status: 5 },
eventId: "test_event_id"
});
2.5 Super properties
Some important properties, such as the user's device ID, source channel, and user status, need to be set in every event. In this case, you can set them as super properties, which are carried by every event. We recommend that you set super properties before sending events.
2.5.1 Static super properties
For important properties that need to be set in every event, such as the user's channel, nickname, and ID, you can call setSuperProperties to set static super properties. Static super properties take effect globally.
// Set super properties. All data events will carry these properties
TDAnalytics.setSuperProperties({
channel: "Channel Name",
user_name: "User Name"
});
In addition to setting properties, we also provide other APIs for working with static super properties to meet day-to-day business needs.
// Get static super properties
let superProperties = TDAnalytics.getSuperProperties();
// Clear a static super property. For example, clear the previously set 'channel' property, and subsequent data will not carry this property
TDAnalytics.unsetSuperProperty("channel");
// Clear all static super properties
TDAnalytics.clearSuperProperties();
2.5.2 Dynamic super properties
Use setDynamicSuperProperties to set the callback function for dynamic super properties. The SDK triggers the callback function when an event is reported and adds the returned JSON object to the event properties. The parameter of setDynamicSuperProperties is a function, and the function must return a JSON object.
// Set dynamic super properties. The callback function is triggered when an event is reported, and the returned JSON object is added to the event properties
TDAnalytics.setDynamicSuperProperties(() => {
return {
dy_name: 'xxx',
dy_age: 18
}
})
2.6 Track event duration
To record how long an event lasts, call timeEvent to start timing. Specify the name of the event you want to time; when you upload that event, the #duration property is automatically added to its event properties to indicate the recorded duration in seconds. Note that only one timing task can run for the same event name at a time.
//The following example measures how long a user stays on a product page
TDAnalytics.timeEvent("stay_shop");
/**do someting
.......
**/
//The user leaves the product page and timing ends. The "stay_shop" event will carry the #duration property that indicates the event duration
TDAnalytics.track({
eventName: "stay_shop",
properties: {
product_name: "Product Name"
}
});
3. User properties
The user property APIs supported by the TA platform are: userSet, userSetOnce, userAdd, userUnset, userDelete, userAppend, and userUniqAppend.
3.1 userSet
For general user properties, you can call userSet to set them. Properties uploaded through this API overwrite the existing property values. If the user property does not exist yet, it is created with the same type as the value passed in. The following example sets the user name:
// username is TA
TDAnalytics.userSet({
properties: {
username: "TA"
}
});
//username is AE
TDAnalytics.userSet({
properties: {
username: "TE"
}
});
3.2 userSetOnce
If a user property only needs to be set once, you can call userSetOnce to set it. If the property already has a value, this call is ignored. The following example sets the first payment time:
//first_payment_time is 2018-01-01 01:23:45.678
TDAnalytics.userSetOnce({
properties: {
first_payment_time: "2018-01-01 01:23:45.678"
}
});
//first_payment_time is still 2018-01-01 01:23:45.678
TDAnalytics.userSetOnce({
properties: {
first_payment_time: "2018-12-31 01:23:45.678"
}
});
3.3 userAdd
When you upload a numeric property, you can call userAdd to accumulate its value. If the property has not been set yet, it is assigned 0 before the calculation. Passing a negative value is equivalent to subtraction.
//total_revenue is now 30
TDAnalytics.userAdd({
properties: {
total_revenue: 30
}
});
//total_revenue is now 678
TDAnalytics.userAdd({
properties: {
total_revenue: 648
}
});
3.4 userUnset
When you need to clear a user's property value, you can call userUnset to clear the specified property. If the property has not been created in the cluster yet, userUnset does not create it
// Clear the value of the user property named userPropertykey for this user, that is, set it to NULL
TDAnalytics.userUnset({
property: "userPropertykey"
});
3.5 userDelete
To delete a user, you can call userDelete. After that, you can no longer query this user's user properties, but the events generated by the user can still be queried.
TDAnalytics.userDelete();
3.6 userAppend
You can call userAppend to append elements to user data of the array type.
TDAnalytics.userAppend({
properties: {
user_list: ["apple", "ball"]
}
});
3.7 userUniqAppend
You can call userUniqAppend to append unique elements to user data of the Array (List) type. userUniqAppend deduplicates the appended user property values, while userAppend does not, so the user property may contain duplicates.
//The value of user_list is now ["apple","ball"]
TDAnalytics.userAppend({
properties: {
user_list: ["apple", "ball"]
}
});
//The value of user_list is now ["apple","apple","ball","cube"]
TDAnalytics.userAppend({
properties: {
user_list: ["apple", "cube"]
}
});
//The value of user_list is now ["apple","ball","cube"]
TDAnalytics.userUniqAppend({
properties: {
user_list: ["apple", "cube"]
}
});
4. Encryption
The SDK supports encrypting data with AES+RSA. Data encryption requires cooperation between the client and the server. For details, contact your customer success representative.
let config = new TDConfig()
config.appId = 'app_id'
config.serverUrl = 'server_url'
//Enable encryption and set the public key information
config.enableEncrypt(1,'publicKey')
TDAnalytics.initWithConfig(context, config)
5. Integrate with H5 pages
To connect with the JavaScript SDK that collects H5 page data, call the following API when you initialize the WebView
controller: webview.WebviewController = new webview.WebviewController();
TDAnalytics.setJsBridge(controller)
6. Other features
6.1 Get the device ID
You can call getDeviceId() to get the device ID.
let deviceId = TDAnalytics.getDeviceId();
The device ID is saved in the cache. If the user clears the cache, the device ID is reset.
6.2 Calibrate time
By default, the SDK uses the local device time as the event time. If users manually change the device time, your business analysis may be affected. In this case, you can calibrate the time to keep the event time accurate. We provide two time calibration methods: timestamp, automatic.
- You can calibrate the SDK time with the current timestamp obtained from the server. After that, all calls that don't specify a time, including event data and user property operations, use the calibrated time as the time of occurrence.
// 1585633785954 is the current Unix timestamp in milliseconds, corresponding to Beijing time 2020-03-31 13:49:45
TDAnalytics.calibrateTime(1585633785954)
- You can also enable automatic time calibration. The SDK then tries to get the current time from the config API and calibrates the SDK time. If no correct response is received, data is reported with the local time afterward.
let config = new TDConfig()
config.appId = 'appId'
config.serverUrl = 'serverUrl'
//Set to true to enable automatic time calibration
config.enableAutoCalibrated = true
TDAnalytics.initWithConfig(context, config)
6.3 Set the default time zone
By default, the SDK uses the local device time as the event time. You can also specify a time zone through the API for setting the default time zone, so that the event time of all events is aligned to the time zone you set:
import I18n from '@ohos.i18n';
let config = new TDConfig()
config.appId = 'appId'
config.serverUrl = 'serverUrl'
config.defaultTimeZone = 8
TDAnalytics.initWithConfig(this.context, config)
Aligning the event time to a specified time zone discards the device's local time zone information. To keep the device's local time zone information, you currently need to add the relevant property to events yourself.
6.4 Flush data immediately
In some business scenarios, if you want data to be reported to the AE server immediately, you can call the flush API
TDAnalytics.flush();
6.5 GZIP-compressed reporting
Starting from 1.8.0, the SDK supports gzip-compressed data reporting. To enable it:
ohpm install @ohos/flate2
Or add the dependency under dependencies:
"dependencies": {
"@ohos/flate2": "1.0.0"
}
Then enable gzip compression in the initialization configuration:
import { gzip } from "@ohos/flate2"
let config = new TDConfig()
config.appId = 'appId'
config.serverUrl = 'serverUrl'
config.enableAutoCalibrated = true
//Enable gzip compression. Defaults to false. When enableGzip is true, you must set gzipFun; otherwise gzip compression cannot be enabled
config.enableGzip = true
config.gzipFun = gzip
TDAnalytics.initWithConfig(this.context, config)
We recommend flate2, a high-performance library optimized for HarmonyOS that can operate on compressed data directly and performs better than pako. pako is slow and performs poorly, so we don't recommend it.

