Skip to main content

Advanced guide

Last updated 10/02/2026

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​

tip

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
String 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.

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:

//Store purchase event
try {
JSONObject properties = new JSONObject();
properties.put("product_name","Product Name");
TDAnalytics.track("product_buy",properties);
} catch (JSONException e) {
e.printStackTrace();
}

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.

JSONObject properties = new JSONObject();
try {
properties.put("key", "value");
} catch (JSONException e) {
e.printStackTrace();
}

TDAnalytics.track(new TDFirstEventModel("device_activation", properties));

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
TDFirstEventModel model = new TDFirstEventModel("device_activation", properties);
model.setFirstCheckId("TA");
TDAnalytics.track(model);

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
JSONObject properties = new JSONObject();
try {
properties.put("status", 3);
properties.put("price", 100);
} catch (JSONException e) {
e.printStackTrace();
}
TDAnalytics.track(new TDUpdatableEventModel("UPDATABLE_EVENT", properties, "test_event_id"));
// After reporting, the event property status is updated to 5 and price is unchanged
JSONObject properties_new = new JSONObject();
try {
properties_new.put("status", 5);
} catch (JSONException e) {
e.printStackTrace();
}
TDAnalytics.track(new TDUpdatableEventModel("UPDATABLE_EVENT", properties_new, "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
JSONObject properties = new JSONObject();
try {
properties.put("status", 3);
properties.put("price", 100);
} catch (JSONException e) {
e.printStackTrace();
}
TDAnalytics.track(new TDOverWritableEventModel("OVERWRITE_EVENT", properties, "test_event_id"));
// After reporting, the event property status is updated to 5 and the price property is deleted
JSONObject properties_new = new JSONObject();
try {
properties_new.put("status", 5);
} catch (JSONException e) {
e.printStackTrace();
}
TDAnalytics.track(new TDOverWritableEventModel("OVERWRITE_EVENT", properties_new, "test_event_id"));

2.5 Super properties​

Super properties are properties that are uploaded with every event. Based on how often they are updated, super properties are divided into static super properties and dynamic super properties. You can choose different ways to set super properties based on your business scenarios; we recommend setting super properties before sending events. For the same event, when a super property, a custom event property, and a preset property have the same key, values are assigned in the following order of priority: custom properties > dynamic super properties > static super properties > preset properties.

2.5.1 Static super properties​

Static super properties are properties that change infrequently and are carried by every event, such as a user's membership level. After you set static super properties through setSuperProperties, the SDK adds them to each event as event properties when the event is collected.

//Set super properties
try {
JSONObject superProperties = new JSONObject();
superProperties.put("vip_level",2);
TDAnalytics.setSuperProperties(superProperties);
} catch (JSONException e) {
e.printStackTrace();
}

Static super properties are saved in the cache, so you don't need to set them every time the app starts. If a property already exists, the newly set value overwrites the original value; if the property doesn't exist, a new property is created. In addition to setting properties, we also provide other APIs for managing static super properties to meet everyday business needs.

//Clear a super property
TDAnalytics.unsetSuperProperty("Channel");
//Clear all super properties
TDAnalytics.clearSuperProperties();
//Get all super properties
TDAnalytics.getSuperProperties();

2.5.2 Dynamic super properties​

Dynamic super properties are properties that change frequently and are carried by every event, such as the number of coins a user has. After you set the dynamic super property class through setDynamicSuperPropertiesTracker, the SDK automatically gets the properties in getDynamicSuperProperties when an event is collected and adds them to the triggered event.

int coin = 0;
TDAnalytics.setDynamicSuperProperties(new TDAnalytics.TDDynamicSuperPropertiesHandler() {
@Override
public JSONObject getDynamicSuperProperties() {
JSONObject dynamicSuperProperties = new JSONObject();
coin++;//The number of coins updates frequently
try {
dynamicSuperProperties.put("coin",coin);
} catch (JSONException e) {
e.printStackTrace();
}
return dynamicSuperProperties;
}
});

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
try {
//The user enters the product page and timing starts
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("stay_shop");
} catch (JSONException e) {
e.printStackTrace();
}

3. User properties​

The user property APIs supported by AE 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 original values. If the user property doesn't exist yet, it is created with the same type as the value passed in. The following example sets the username:

try {
//username is now TA
JSONObject properties = new JSONObject();
properties.put("username","TA");
TDAnalytics.userSet(properties);
//userName is now AE
JSONObject newProperties = new JSONObject();
newProperties.put("username","TE");
TDAnalytics.userSet(newProperties);
} catch (JSONException e) {
e.printStackTrace();
}

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:

try {
//first_payment_time is 2018-01-01 01:23:45.678
JSONObject properties = new JSONObject();
properties.put("first_payment_time","2018-01-01 01:23:45.678");
TDAnalytics.userSetOnce(properties);

//first_payment_time is still 2018-01-01 01:23:45.678
JSONObject newProperties = new JSONObject();
newProperties.put("first_payment_time","2018-12-31 01:23:45.678");
TDAnalytics.userSetOnce(newProperties);

} catch (JSONException e) {
e.printStackTrace();
}

3.3 userAdd​

To accumulate a numeric property, you can call userAdd. If the property hasn't been set yet, it is assigned 0 before the calculation. You can pass in a negative value, which is equivalent to subtraction. The following example accumulates the total payment amount:

try {
//total_revenue is now 30
JSONObject properties = new JSONObject();
properties.put("total_revenue",30);
TDAnalytics.userAdd(properties);

//total_revenue is now 678
JSONObject newProperties = new JSONObject();
newProperties.put("total_revenue",648);
TDAnalytics.userAdd(newProperties);
} catch (JSONException e) {
e.printStackTrace();
}

3.4 userUnset​

To clear the value of a user property, you can call userUnset to clear the specified property. If the property hasn't been created in the cluster yet, userUnset does not create it

// Reset a single user property
TDAnalytics.userUnset("key1");
// Reset multiple user properties
TDAnalytics.userUnset("key1", "key2", "key3");

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 an array-type user property.

try {
// list is the value of the user property user_list, of type JSONArray
JSONArray list = new JSONArray("[\"apple\", \"ball\"]");
JSONObject properties = new JSONObject();
properties.put("user_list", list);
// Call user_append to append elements to the user property user_list. If it does not exist, it is created
TDAnalytics.userAppend(properties);
} catch (JSONException e) {
e.printStackTrace();
}

3.7 userUniqAppend​

You can call userUniqAppend to append elements to an array-type user property. Calling userUniqAppend deduplicates the appended user property values, whereas the userAppend API doesn't deduplicate, so the user property may contain duplicates.

try {
// list is the value of the user property user_list, of type JSONArray
//The value of user_list is now ["apple", "ball"]
JSONArray list = new JSONArray("[\"apple\", \"ball\"]");
JSONObject properties = new JSONObject();
properties.put("user_list", list);
TDAnalytics.userAppend(properties);


//The value of user_list is now ["apple","apple","ball","cube"]
JSONArray list1 = new JSONArray("[\"apple\", \"cube\"]");
JSONObject properties1 = new JSONObject();
properties1.put("user_list", list1);
TDAnalytics.userAppend(properties1);

//The value of user_list is now ["apple", "ball","cube"]
TDAnalytics.userUniqAppend(properties1);

} catch (JSONException e) {
e.printStackTrace();
}

4. Encryption​

Starting from v2.8.0, 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.

TDConfig config = TDConfig.getInstance(mContext,TA_APP_ID,TA_SERVER_URL);
//Enable encryption and set the public key
config.enableEncrypt(1,"publicKey")

5. Integrate with H5 pages​

To integrate with the JavaScript SDK that collects H5 page data, call the following API when initializing the WebView. For details, see H5 and App SDK integration

// Connect H5 page data
TDAnalytics.setJsBridge(webView);

6. Other features​

6.1 Get the device ID​

You can call getDeviceId to get the device ID:

String deviceID = TDAnalytics.getDeviceId();//The device ID is the Android ID

6.2 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:

// Get the TDConfig instance
TDConfig config = TDConfig.getInstance(this, TA_APP_ID, TA_SERVER_URL);
// Set the default time zone to UTC
config.setDefaultTimeZone(TimeZone.getTimeZone("UTC"));
// Initialize the SDK
TDAnalytics.init(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.3 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 and NTP (时间戳、NTP).

  • 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 set an NTP server address. The SDK then tries to get the current time from that NTP server and calibrates the SDK time. If no correct response is received within the default timeout (3 seconds), data is reported with the local time afterward.
// Calibrate time with the Apple NTP service
TDAnalytics.calibrateTimeWithNtp("time.apple.com");

1. Time calibration with an NTP service involves some uncertainty. We recommend calibrating with a timestamp whenever possible.

2. Choose your NTP server address carefully so that user devices can quickly get the server time when the network is in good condition.

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 Get the country/region code​

In some business scenarios, if you need to know the country/region code of the user's device, you can get it through getLocalRegion

TDAnalytics.getLocalRegion();

6.6 Disable Android ID collection​

If you don't want code that collects the Android ID in your project, you can use the plugin to isolate code for sensitive properties (such as AndroidID).

Android analytics SDK versionPlugin version
[oldest - 3.0.0)1.2.0
[3.0.0 - 3.1.0]2.1.0
(3.1.0 - latest]2.2.0
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'cn.thinkingdata.android:android-gradle-plugin2:2.2.0'
}
}
// Configure disableAndroidID to true in the project build.gradle file
apply plugin: 'cn.thinkingdata.android'
android {}
ThinkingAnalytics {
debug = true
sdk{
disableAndroidID = true
}
}

Parameters:

  • debug: whether to enable compile logs. true enables compile logs. The default is false.
  • exclude: excludes classes under a path from scanning. You can set exclude = ['cn.thinkingdata.android','android.support'].
  • useInclude, include: to scan only classes under a path, set useInclude = true and include= ['cn.thinkingdata.android','android.support'].
  • disableAndroidID: whether to disable calling the system API to get the AndroidID. Starting from plugin V2.1.0, you can configure it by setting disableAndroidID = true.

6.7 Report data via IP​

To prevent or resolve issues where client data can't be reported to the server because of DNS hijacking, the SDK resolves the ServerUrl to get the IP and then reports data directly to the server via the IP. The following example shows how to enable it:

TDConfig config = TDConfig.getInstance(this, APPID, TE_SERVER_URL);
List<TDConfig.TDDNSService> list = new ArrayList<>();
list.add(TDConfig.TDDNSService.CLOUD_ALI);
list.add(TDConfig.TDDNSService.CLOUD_FLARE);
list.add(TDConfig.TDDNSService.CLOUD_GOOGLE);
config.enableDNSService(list);

6.8 SDK error callback​

note

Requires Android SDK version >= 3.2.0

In some scenarios, you may want to perform custom actions when a network request fails. In this case, you can register an errorCallback, as shown in the following example:

TDAnalytics.registerErrorCallback(new TDAnalytics.TDSendDataErrorCallback() {
@Override
public void onSDKErrorCallback(int code, String errorMsg, String ext) {
// todo
}
});

Error codes for code

Error codeDescription
1001Network request failed

6.9 Disable fetching configuration on initialization​

Starting from version 3.4.0, if you don't need to fetch configuration when the SDK is initialized, you can turn it off through disableRConfig. The code is as follows:

TDConfig config = TDConfig.getInstance(this, APPID, TE_SERVER_URL);
config.disableRConfig = true;
TDAnalytics.init(config);

6.10 Configure backup reporting URLs​

Starting from version 3.4.0, if you need to configure multiple reporting URLs, you can configure them through backupUrlList. Sample code:

TDConfig config = TDConfig.getInstance(this, APPID, TE_SERVER_URL);
List<String> backupUrlList = new ArrayList<>();
backupUrlList.add("serverurl1");
backupUrlList.add("serverurl2");
backupUrlList.add("serverurl3");
config.backupUrlList = backupUrlList;
TDAnalytics.init(config);
Was this page helpful?