目录
此内容是否有帮助?

# Android SDK User Guide

TIP

Before accessing, please read the preparation before accessing .

You can get the Android SDK source code on GitHub (opens new window).

The Android SDK requires a minimum system version of Android 4.0 (API 14)

Android SDK (aar format) size is about 1 61 KB

**The latest version is: **2.7.6.1

**Updated: **2022 - 02 - 07

Download address (opens new window)

# I. Initialization of SDK

# 1.1 Automatically Integrate Android SDK

  • Add the following configuration dependencies to the Project-level build.gradlefile
buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
}
  • Add dependencies to the build.gradlefile in the Moduleproject directory:

Note: v2.1.0 version changed the package name, the old package name can be used at the same time, but the new features will not be updated later, please pay attention to adjust the package name when upgrading from the old version to the new version

dependencies {
    implementation 'cn.thinkingdata.android:ThinkingAnalyticsSDK:2.7.6.1'
}

# 1.2 Manually Integrate the Android SDK

  1. Download and extract the Android SDK (opens new window)

  2. Add ThinkingSDK.aar to libs folder

  3. In build.gradle add the following configuration

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar','*.aar'])
}

# 1.3 Initialize SDK

In v1.3.0 version, the new multi-APP ID instance features, added a new initialization method, for the use of multi-APP ID guide, please refer to the Android SDK multi-APPID guide section.

Used in the onCreate method of the application's Application class.

// Initialize SDK in main thread
ThinkingAnalyticsSDK instance = ThinkingAnalyticsSDK.sharedInstance(this, TA_APP_ID, TA_SERVER_URL);

// Events can be subsequently reported using the SDK in two ways
instance.track("some_event");
ThinkingAnalyticsSDK.sharedInstance(this, TA_APP_ID).track("some_event");

// Prior to 1.3.0, or a single instance can initialize and use SDK using the following methods
// ThinkingAnalyticsSDK.sharedInstance(this, TA_APP_ID);
// ThinkingAnalyticsSDK.sharedInstance(this).track("some_event");

Parameter description:

  • TA_APP_ID: Is the APP ID of your project, which can be obtained from the TA project management page.
  • TA_SERVER_URL: URL for data upload
    • If you are connecting to Cloud as a Service, fill in: https://receiver.ta.thinkingdata.cn
    • If you use the customized deployment version, bind the domain name for the data acquisition address and configure the HTTPS certificate: https://Data acquisition address bind domain name.

Since Android 9.0 + limits HTTP requests by default, be sure to use the HTTPS protocol

Starting with v2.3.0, the configuration class TDConfigis supported for initialization. Use TDConfigto personalize more of the SDK's capabilities.

// Get an instance of TDConfig
TDConfig config = TDConfig.getInstance(this, TA_APP_ID, TA_SERVER_URL);

// Initialise SDK
ThinkingAnalyticsSDK instance = ThinkingAnalyticsSDK.sharedInstance(config);

Starting from v2.7.3, add the field instance name, and pass in the instance name namewhen the instance is initialized to identify the instance. You can also get instances by name.

// Get an example of TDConfig and pass it in to NAME
TDConfig config = TDConfig.getInstance(this, TA_APP_ID, TA_SERVER_URL, TA_CONFIG_NAME);

// Initialise SDK
ThinkingAnalyticsSDK instance = ThinkingAnalyticsSDK.sharedInstance(config);

# 1.4 Open the H5 Page (Optional)

If you need to get through with the JavaScript SDK that collects H5 page data, call the following interface when initializing the WebView. For details, please refer to the H5 and APP SDK get through section.

// Get through H5 page data
instance.setJsBridge(webView);
// ThinkingAnalyticsSDK.sharedInstance(this, TA_APP_ID).setJsBridge(webView);

// Use method of single instance
// ThinkingAnalyticsSDK.sharedInstance(this).setJsBridge(webView);

# II. Set User ID

The SDK instance uses a random UUID as the default visitor ID for each user, which will be used as the user's ID in the logged-in state. It is important to note that the visitor ID will change when the user re-installs App and replaces the device.

# 2.1 Set Visitor ID (optional)

TIP

In general, you do not need to customize the visitor ID. Please make sure that you understand the user identification rules before setting the visitor ID.

If you need to replace the visitor ID, the use should be made immediately after the end of the SDK initialization, do not make multiple use to avoid generating useless accounts.

If your app has its own visitor ID management system for each user, you can use identifyto set the guest ID:

// Set Visitor ID to 123456789ABCabc
instance.identify("123456789ABCabc");

If you need to get the current visitor ID, you can use getDistinctIdto get:

//Returns the visitor ID. in the case of multiple instances, the visitor ID of the calling instance is returned
String distinctId = instance.getDistinctId();

# 2.2 Set Account ID

When the user logs in, you can use loginto set the user's account ID. After setting the account ID, the account ID will be used as the identification ID, and the set account ID will be used logout. It has been retained until:

instance.login("1234567@thinkinggame.cn");

Logincan be used many times. Each call will determine whether the incoming account ID is consistent with the previously saved ID. If it is consistent, the use will be ignored, and if it is inconsistent, the previous ID will be overwritten.

Note that this method does not upload events for user logins

# 2.3 Clear Account ID

After the user produces login behavior, you can use logoutto clear the account ID. Before the next use to login, the visitor ID will be used as the identification ID:

instance.logout();

We recommend that you use logoutduring explicit logout events, such as when the user logs off the account, rather than when the app is closed.

Note that this method does not upload user logged-out events**.**

# III. Send Event

After the SDK initialization is completed, you can use trackto upload events. In general, you may need to upload more than a dozen to hundreds of different events. If you are using the TA for the first time, we recommend you upload a few key events first.

# 3.1 Send events

You can use trackto upload events. It is recommended that you set the properties of the event and the conditions for sending information according to the previously sorted documents. Here, take the user's purchase of a commodity as an example:

//Store purchase event
try {
    JSONObject properties = new JSONObject();
    properties.put("product_name","Trade Name");
    properties.put("product_num",1);
    properties.put("Cost",100);
    properties.put("isFirstBuy",true);
    instance.track("product_buy",properties);
} catch (JSONException e) {
    e.printStackTrace();
}

The name of the event is of type Stringand can only begin with a letter. It can contain numbers, letters and an underscore "_". The maximum length is 50 characters and is not sensitive to letter case.

  • The property of the event is a JSONObjectobject where each element represents a property.
  • The value of Key is the name of the attribute, which is of Stringtype. It can only start with a letter, contain numbers, letters and underscore "_", and is up to 50 characters in length. It is not sensitive to letter case.
  • Value is the value of the property and supports String, Number, Boolean, Dateand JSONArray. For JSONArrayelements, only the string type is supported, and all other types will be forced into string storage.

Note: JSONArray type is supported in v2.4.0 version, and needs to be used with TA background v2.5 and subsequent versions.

In v2.2.0 version, the method overload of setting event trigger time and time offset is added. It supports passing in Datetype parameters to set event trigger time and TimeZonetype parameters to set time offset. If this parameter is not passed in, the local time and offset when the trackis called are taken as the event trigger time and time zone offset:

try {
    JSONObject properties = new JSONObject();
    properties.put("product_name","Trade name");
    properties.put("product_num",1);
    properties.put("Cost",100);
    properties.put("isFirstBuy",true);
    instance.track("product_buy", properties, new Date(), TimeZone.getDefault());
} catch (JSONException e) {
    e.printStackTrace();
}

Note: Although the trigger time can be set for the event, the receiving end will only receive data from the first 10 days to the last 3 days relative to the server time. Data exceeding the time limit will be regarded as abnormal data, and the entire data cannot be stored.

Since v2.3.1, you can align event times across multiple time zones by setting the SDK's default time zone, see the Setting Default Time Zones section . Starting from v2.5.0, you can use server level time to complete data collection by calibrating the SDK time interface. Please refer to the Calibration Time section .

# 3.2 Set Public Event Attributes

For some important attributes, such as the user's membership level, source channel, etc., 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 setSuperPropertiesto set the public event property. We recommend that you set the public event property before sending the event.

Format requirements for public event attributes are consistent with event attributes.

//Set Common Event Properties
try {
    JSONObject superProperties = new JSONObject();
    superProperties.put("vip_level",2);
    superProperties.put("Channel","A1");
    instance.setSuperProperties(superProperties);
} catch (JSONException e) {
    e.printStackTrace();
}

//Upload events using track with common event attributes
try {
    JSONObject properties = new JSONObject();
    properties.put("product_id","A1354");
    instance.track("product_pay",properties);
} catch (JSONException e) {
    e.printStackTrace();
}

//Equivalent to adding these attributes to each event
try {
    JSONObject properties = new JSONObject();
    properties.put("vip_level",2);
    properties.put("Channel","A1");
    properties.put("product_id","A1354");
    instance.track("product_pay",properties);
} catch (JSONException e) {
    e.printStackTrace();
}

The public event attributes will be saved to the cache and need not be called every time the app is started. If the call to setSuperPropertiesuploads a previously set public event attribute, the previous attribute is overwritten. If the public event attribute and the Key of a attribute uploaded by trackduplicate, the attributes of the event override the attributes of the public event:

//Taking on the previous example, the attributes of public events at this time are "Channel" 与 "vip_level"
try {
    JSONObject superProperties = new JSONObject();
    superProperties.put("Channel","B1");        //"Channel"Covered
    instance.setSuperProperties(superProperties);
} catch (JSONException e) {
    e.printStackTrace();
}

try {
    JSONObject properties = new JSONObject();
    properties.put("product_id","A1354");
    properties.put("vip_level",3);            //"vip_level"Covered
    instance.track("product_pay",properties);
} catch (JSONException e) {
    e.printStackTrace();
}

//Attributes in the data received "Channel" is "B1","vip_level" is 3

If you need to delete a public event property, you can use unsetSuperPropertyto clear one of the public event properties;

If you want to empty all public event properties, you can use clearSuperProperties;

If you want to get all public event properties, you can use getSuperProperties;

//Clear a common event attribute,for example, if you clear the previously set Channel property, the data after that will not have that property
instance.unsetSuperProperty("Channel");

//Clear all public event attributes
instance.clearSuperProperties();

//Get all public event attributes
instance.getSuperProperties();

# 3.3 Set Dynamic Public Attributes

In v1.3.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. After setting the dynamic public attribute class through the setDynamicSuperPropertiesTracker, the SDK will automatically get the attributes in the getDynamicSuperPropertieson the event report and add them to the triggered event. The following example adds the time to the event every time it is reported. When the event is triggered, the return value of getDynamicSuperPropertieswill be added to the event attribute.

// Set dynamic public attributes to dynamically capture when an event occurs when it is reported
instance.setDynamicSuperPropertiesTracker(
    new ThinkingAnalyticsSDK.DynamicSuperPropertiesTracker() {

        // Overwrite getDynamicSuperProperties to set the method for obtaining attribute values for dynamic common attributes
        @Override
        public JSONObject getDynamicSuperProperties() {
            JSONObject dynamicSuperProperties = new JSONObject();
            String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
            SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern,Locale.CHINA);
            String timeString = sDateFormat.format(new Date());
            try {
                dynamicSuperProperties.put("dynamicTime", timeString);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return dynamicSuperProperties;
        }
    });

# 3.4 Record the Duration of the Event

If you need to record the duration of an event, you can call timeEventto start timing, configure the event type you want to time, and when you upload the event, it will be automatically added to your event property #durationThis property represents the duration of the recording, in seconds. It should be noted that only one task can be timed with the same event name.

try {
    //The user enters the merchandise page and starts the timing with the events recorded as "Enter_Shop"
    instance.timeEvent("Enter_Shop");

    //Set event attributes, commodity ID browsed by user
    JSONObject properties = new JSONObject();
    properties.put("product_id","A1354");

    //Upload Event, Clock Ended,"Enter_Shop" this event will have an attribute indicating the length of the event #duration
    instance.track("Enter_Shop",properties);
} catch (JSONException e) {
    e.printStackTrace();
}

# IV. User Features

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_setto set it. The attributes uploaded using this interface will overwrite the original attribute values. If the user feature does not exist before, the new user feature will be created. The type is the same as the type of the passed-in attribute. Take setting the user name as an example:

try {
    JSONObject properties = new JSONObject();
    properties.put("UserName","ABC");
    instance.user_set(properties);
    //Now "UserName"is "ABC"

    JSONObject newProperties = new JSONObject();
    newProperties.put("UserName","abc");
    instance.user_set(newProperties);
    //Now "UserName" is "abc"

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

The user feature format user_set set requires consistency with event properties.

# 4.2 User_setOnce

If the user feature you want to upload only needs to be set once, you can use user_setOnceto set it. When the attribute already has a value before, this information will be ignored. Take setting the first payment time as an example:

try {
    JSONObject properties = new JSONObject();
    properties.put("FirstPaidTime","2018-01-01 01:23:45.678");
    instance.user_setOnce(properties);
    //Now "FirstPaidTime" is "2018-01-01 01:23:45.678"

    JSONObject newProperties = new JSONObject();
    newProperties.put("FirstPaidTime","2018-12-31 01:23:45.678");
    instance.user_setOnce(newProperties);
    //Now "FirstPaidTime" is "2018-01-01 01:23:45.678"

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

The user feature format set by user_setOnce requires consistency with event properties.

# 4.3 User_add

When you want to upload a numeric attribute, you can call user_addto 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. Take the accumulated payment amount as an example:

try {
    JSONObject properties = new JSONObject();
    properties.put("TotalRevenue",30);
    instance.user_add(properties);
    //Now "TotalRevenue"is 30

    JSONObject newProperties = new JSONObject();
    newProperties.put("TotalRevenue",648);
    instance.user_add(newProperties);
    //Now "TotalRevenue"is 678

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

The property type user_add set and the limits on the Key value are consistent with user_set, but Value only allows the Number type.

# 4.4 User_unset

When you want to empty the user feature value of the user, you can use user_unsetto empty the specified attribute. If the attribute has not been created in the cluster, user_unset **will not **create the attribute.

// Reset individual user attributes
instance.user_unset("key1");

// Reset multiple user attributes
instance.user_unset("key1", "key2", "key3");

// Reset multiple user attributes, pass in string array
String[] keys = {"key1", "key2"};
instance.user_unset(keys);

user_unset The parameter passed in is the property name of the user feature, and the type is string or string array, which supports the form of variable-length parameters.

# 4.5 User_delete

If you want to delete a user, you can call user_deleteto delete the user. You will no longer be able to query the user features of the user, but the events generated by the user can still be queried.

instance.user_delete();

# 4.6 User_append

Starting with v2.4.0, you can use user_appendappend to user features of type JSONArray.

try {
    // list is user attribute user_list value,JSONArray type
    JSONArray list = new JSONArray("[\"apple\", \"ball\"]");
    JSONObject properties = new JSONObject();
    properties.put("user_list", list);

    // Use user_append as user attribute, user_list creation. If not,new element will be created.
    mInstance.user_append(properties);
} catch (JSONException e) {
    e.printStackTrace();
}

# V. Automatic Acquisition Events

The Android SDK supports automatic collection of some events, including installation, startup, shutdown, etc.

For details on how to use automatic collection events, please refer to the chapter of the Android SDK Automatic Collection Guide .

# VI. SDK Configuration

This section describes some of the interfaces and options related to SDK configuration. Since the SDK itself supports multiple instances, some of the configurations of the SDK are global configurations for all instances, and some are configurations for a single instance.

  • Global configuration: generally configured through AndroidM anifest.xml, or through static method use.
  • Single instance configuration: Configure by using the instance method.

# 6.1 Set the upload network conditions

By default, the SDK instance will upload data in 2G, 3G, 4G, 5G and Wifi. You can modify the network conditions that allow uploading by the following methods:

//Report data only in Wifi environment
instance.setNetworkType(NETWORKTYPE_WIFI);

//Upload data on 2G, 3G, 4G, 5G and Wifi with default setting
instance.setNetworkType(NETWORKTYPE_DEFAULT);

//Upload data on 2G, 3G, 4G, 5G and Wifi
instance.setNetworkType(NETWORKTYPE_ALL);

# 6.2 Print Upload Data Log

In version v1.1.7, the function of printing logs has been added. You can add the following code to the applicationlabel in the AndroidM anifest.xml to turn on the printing log function (it is turned off by default):

<application...>
    .....
    <meta-data
        android:name="cn.thinkingdata.android.EnableTrackLogging"
        android:value="true" />
</application>

In v2.0.0, an interface for printing logs has been added. You can use enableTrackLogto turn it on (it is turned off by default):

ThinkingAnalyticsSDK.enableTrackLog(true);

After opening the log, you can filter the log related to ThinkingAnalytics to observe the data reporting of the SDK.

# 6.3 Get Device ID

In v2.0.0, an interface was added to get the device ID (that is, the preset attribute #device_id). You can get the device ID by calling getDeviceId:

 instance.getDeviceId();

 //If you need to set the device ID to the visitor ID, you can call it as follows
 //instance.identify(instance.getDeviceId());

# 6.4 Pause/Stop Data Reporting

In v2.1.0 version, the function of stopping SDK instance reporting data has been added. There are two types of interfaces to stop SDK instance reporting:

# 6.4.1 Pause SDK reporting (enableTracking)

You may want to temporarily stop data collection and reporting in some scenarios, such as when the user is in a test environment or when the user logs into a test account, you can call the following interfaces to temporarily stop reporting an SDK instance.

You can use enableTrackingthrough an instance (including the main instance and the light instance), pass in falseto suspend the reporting of the SDK instance. The #distinct_id, #account_id, public attributes that have been 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 you can read the public attributes and device IDs, visitor IDs, account IDs etc. that the instance has set.

The stop state of the instance will be saved in the local cache until the enableTrackingis called, and trueis passed in. The SDK instance will resume data collection and reporting. It is necessary to pay attention to the light instance because it 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 re-opened.

// Pause reporting
instance.enableTracking(false);

// Restore reporting
instance.enableTracking(true);

# 6.4.2 Stop SDK reporting (optOutTracking)

In some special situations, you may need to completely stop the function of the SDK instance. For example, in areas where GDPR is applicable, the user chooses not to provide data collection permissions, you can use the following interface to completely turn off the function of the SDK instance.

OptOutTrackingcan only be used through the main instance. The biggest difference with enableTrackingis 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 and reset local caching
instance.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_deldata before stopping the function of the SDK instance to delete the user's user data.

// Stop reporting and send delete user request
instance.optOutTrackingAndDeleteUser();

The stop state of the instance will also be saved in the local cache until the optInTrackingis called, and subsequent reports can continue, but this is equivalent to a brand new instance.

// Re-start reporting
instance.optInTracking();

# 6.5 Set Up Self-sign Certificate

Starting from v2.3.0, the SDK allows custom SSLSocketFactory custom certificate verification to be passed in. In order to set up a self-sign certificate, you need to first obtain a TDConfig instance during initialization, and then complete the initialization with TDConfig. The self-sign is effective for all network requests under this instance.

// Get an example of TDConfig
TDConfig config = TDConfig.getInstance(this, TA_APP_ID, TA_SERVER_URL);
// Set custom SSLSocketFactory
config.setSSLSocketFactory(sslSocketFactory);
// Initialise SDK
instance = ThinkingAnalyticsSDK.sharedInstance(config);

# 6.6 Turn on Debug Mode

Starting from v2.3.0, the client SDK supports Debug mode, which needs to be used in conjunction with TA platform versions after 2.5.

Debug mode may affect the quality of data collection and the stability of the app. It is only used for data verification during the integration phase and should not be used in online environments.

The current SDK instance supports three operating modes, defined in TDConfig:

/**
 * Instance run mode, default to NORMAL mode.
 */
public enum ModeEnum {
    /* In normal mode, data is cached and reported according to certain caching strategies */
    NORMAL,
    /* Debug mode,data are reported item by item. Alert users with logs and exceptions when problems occur*/
    DEBUG,
    /* Debug Only mode,data only checked, not stored */
    DEBUG_ONLY
}

To set the SDK instance running mode, use TDConfigto complete the SDK initialization:

// Get an instance of TDConfig
TDConfig config = TDConfig.getInstance(this, TA_APP_ID, TA_SERVER_URL);
// Set Running Mode to Debug Mode
config.setMode(TDConfig.ModeEnum.DEBUG);
// Initialise SDK
instance = ThinkingAnalyticsSDK.sharedInstance(config);

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

The device ID can be obtained in three ways:

  • #device_id attribute in event data in TA platform.
  • Client log: The device DeviceId is printed after the SDK initialization is completed.
  • Use through the instance interface: get device ID.

# 6.7 Set the Default Time Zone

SDK will use native time as the default time to report events. If the user manually modifies the device time, it will affect your business analysis since v2. Starting with Version 5.0, you can calibrate the time of the SDK using the current time stamp obtained from the server. Thereafter, all unspecified time calls, including event data and user property settings, use the calibrated time as the occurrence time.

// Get an instance of TDConfig
TDConfig config = TDConfig.getInstance(this, TA_APP_ID, TA_SERVER_URL);
// Set default time zone to UTC
config.setDefaultTimeZone(TimeZone.getTimeZone("UTC"));
// Initialise SDK
instance = ThinkingAnalyticsSDK.sharedInstance(config);

Note: Aligning the event time with the specified time zone will lose the device native time zone information. If you need to retain the device native time zone information, you currently need to add relevant attributes for the event yourself.

# 6.8 Calibration Time

The SDK will use the native time as the event occurrence time by default. If the user manually modifies the device time, it will affect your business analysis. Starting from version v2.5.0, you can use the current timestamp obtained from the server level to calibrate the SDK's time. After that, all calls that do not specify a time, including event data and user feature setting operations, will 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
ThinkingAnalyticsSDK.calibrateTime(1585633785954);

We also provide the ability to get time to SDK calibration from NTP. You need to pass in the NTP server address that your users can access. The SDK then attempts to obtain the current time from the incoming NTP service address and calibrate 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
ThinkingAnalyticsSDK.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.

In addition to the above calibration time interface, v2.5.0 provides time function overloading for all user feature interfaces. When you call the user feature related interface, you pass in the date object, and the system will use the incoming Date object to set the data #timefield.

# 6.9 Multi-process Support

In the multi-process business scenario, the SDK does not support direct data reporting in child processes by default; when the SDK is initialized in Application onCreate, it can be set to support multiple processes through TDConfig.

//Support multi-process data acquisition
config.setMutiprocess(true);

Cross-process communication is a relatively slow process and is not turned on by default. It is recommended not to conduct a large number of tracking events in child processes.

Support all UI processes + Service processes.

# 6.10 Global Configuration File

After **V2.7.5 **, a global configuration file for the SDK has been added. You can add ta_public_config.xml file in the res/values directory of the project directory to configure the attribute array that needs to be disabled for collection.

Here are all the attributes that can be disabled:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- ThinkingAnalytics DisablePresetProperties start -->
    <string-array name="TDDisPresetProperties">
<!--        <item>#disk</item>-->
<!--        <item>#fps</item>-->
<!--        <item>#ram</item>-->
<!--        <item>#app_version</item>-->
<!--        <item>#os_version</item>-->
<!--        <item>#manufacturer</item>-->
<!--        <item>#device_model</item>-->
<!--        <item>#screen_height</item>-->
<!--        <item>#screen_width</item>-->
<!--        <item>#carrier</item>-->
<!--        <item>#device_id</item>-->
<!--        <item>#system_language</item>-->
<!--        <item>#lib</item>-->
<!--        <item>#lib_version</item>-->
<!--        <item>#os</item>-->
<!--        <item>#bundle_id</item>-->
<!--        <item>#install_time</item>-->
<!--        <item>#start_reason</item>-->
<!--        <item>#simulator</item>-->
<!--        <item>#network_type</item>-->
<!--        <item>#zone_offset</item>-->
<!--        <item>#start_reason</item>-->
<!--        <item>#resume_from_background</item>-->
<!--        <item>#title</item>-->
<!--        <item>#screen_name</item>-->
<!--        <item>#url</item>-->
<!--        <item>#referrer</item>-->
<!--        <item>#element_type</item>-->
<!--        <item>#element_id</item>-->
<!--        <item>#element_position</item>-->
<!--        <item>#element_content</item>-->
<!--        <item>#element_selector</item>-->
<!--        <item>#app_crashed_reason</item>-->
<!--        <item>#background_duration</item>-->
<!--        <item>#duration</item>-->
    </string-array>
    <!-- ThinkingAnalytics DisablePresetProperties end -->
</resources>

# 6.1 1 Other Global Settings

The SDK can use AndroidM anifest.xmlto modify some global settings. In general, the default settings can be used.

<!-- turn on debug log -->
<meta-data
  android:name="cn.thinkingdata.android.EnableTrackLogging"
  android:value="true"
/>

<!-- Set the database size lower limit (default 32 M) -->
<meta-data
  android:name="cn.thinkingdata.android.MinimumDatabaseLimit"
  android:value="16"
/>

<!-- Set Cached Data Retention Days (default 15 days) -->
<meta-data
  android:name="cn.thinkingdata.android.RetentionDays"
  android:value="7"
/>

<!-- Allow safe exit from service (default is false) -->
<meta-data
  android:name="cn.thinkingdata.android.EnableQuitSafely"
  android:value="true"
/>

<!-- Time-out waiting for each thread (caching, network) to exit when security exit service is turned on, default 2000 ms -->
<meta-data
  android:name="cn.thinkingdata.android.QuitSafelyTimeout"
  android:value="1000"
/>

# VII. Relevant Preset Attributes

# 7.1 Preset Attributes for All Events

The following preset attributes are included with all events in the Android SDK, including AutoCollect events

Attribute name
Chinese name
Description
#ip
IP address
The user's IP address, which the TA will use to obtain the user's geographic location information
#country
Country
User's country, generated according to IP address
#country_code
Country code
The country code of the country where the user is located (ISO 3166-1 alpha-2, that is, two uppercase English letters), generated based on the IP address
#province
Province
The user's province is generated according to the IP address
#city
City
The user's city is generated according to the IP address
#os_version
Operating system version
iOS 11.2.2、Android 8.0.0 等
#manufacturer
Equipment manufacturers
Manufacturers of user equipment, such as Apple, vivo, etc
#os
Operating system
Such as Android, iOS, etc
#device_id
Device ID
The user's device ID, iOS take the user's IDFV or UUID, Android takes androidID
#screen_height
Screen height
The screen height of the user equipment, such as 1920, etc
#screen_width
Screen width
The screen height of the user equipment, such as 1080, etc
#device_model
Equipment model
The model of the user equipment, such as iPhone 8, etc
#app_version
App version
Version of your app
#bundle_id
Application unique identification
Application package name or process name
# lib
SDK type
The type of SDK you access, such as Android, iOS, etc
#lib_version
SDK version
The version you access to the SDK
#network_type
Network status
Network status when uploading events, such as WIFI, 3G, 4G, etc
#carrier
Network Operator
Network operators of user equipment, such as China Mobile, China Telecom, etc
#zone_offset
Time zone offset
The number of hours the data time is offset from UTC time
#install_time
Program installation time
The time the user installs the application, the value comes from the system
#simulator
Yes/No for emulator
Whether the device is emulator true/false
#ram
Device Random Access Memory Status
The current remaining memory and total memory of the user equipment, in GB, such as 1.4/2.4
#disk
Device storage space status
The current remaining storage space and total storage space of the user equipment, in GB, such as 30
/200
# fps
Equipment FPS
The current image transmission frame rate per second of the user equipment, such as 60

# 7.2 Preset Properties for Automatic Acquisition Events

The following preset attributes are unique to each AutoCollect event

  • Preset attributes for APP launch event (ta_app_start)
Attribute name
Chinese name
Description
#resume_from_background
Whether to wake up from the background
Indicates whether the APP is turned on or woken up from the background, the value of true indicates waking up from the background, and false indicates direct opening
#start_reason
Application start source
This property only exists when the application is started in a non-launcher mode, such as the DJ plink mode or other application startup activity.
Sample data: "#start_reason": "{" url ":" thinking data:\/\/"," data ":""}"
#backgroud_duration
Duration of background events
Record the duration of the application entering the background within the interval of the two start events, in seconds
  • Preset attributes for APP shutdown events (ta_app_end)
Attribute name
Chinese name
Description
#duration
Event duration
Represents the duration of the APP visit (from start to end) in seconds
  • Preset attributes for APP browsing page events (ta_app_view)
Attribute name
Chinese name
Description
#title
Page Title
The title of the
Activity
to which the control belongs, with the value of the
title
property of the
Activity
#screen_name
Page name
The package name for the
Activity
to which the control belongs. Class name
#url
Page address
The address of the current page, you need to call
getScreenUrl
to set the url
#referrer
Forward address
The address of the page before the jump, the page before the jump needs to call
getScreenUrl
to set the url
  • Preset attributes for APP control click events (ta_app_click)
Attribute name
Chinese name
Description
#title
Page Title
The title of the
Activity
to which the control belongs, with the value of the
title
property of the
Activity
#screen_name
Page name
The package name for the
Activity
to which the control belongs. Class name
#element_id
Element ID
The ID of the control, the default is
android: id
, you can call
setViewID
to set
#element_type
Element type
Control type
#element_selector
Element selector
Splicing of
viewPath
for controls
#element_position
Element position
Control's position information, uploaded when the control has a
position
property
#element_content
Element content
Content on the control
  • Preset attributes for APP crash events (ta_app_crash)
Attribute name
Chinese name
Description
#app_crashed_reason
Abnormal information
Character type to record the stack trajectory when crashing

# 7.3 Other Preset Properties

In addition to the preset attributes mentioned above, there are also some preset attributes that need to call the corresponding interface to be recorded:

Attribute name
Chinese name
Description
#duration
Event duration
You need to call the timing function interface
timeEvent
to record the duration of the event, in seconds
#backgroud_duration
Backstage event duration
You need to call the timing function interface
timeEvent
to record the duration of the application entering the background within the event occurrence interval in seconds

# 7.4 Get Preset Properties

V2.7.0 and later can use the getPresetProperties ()method to obtain preset attributes.

When some preset attributes on the App are required by the service data reporting, this method can be used to obtain the preset attributes on the App and pass them on to the service.

   //Get Attribute Object
   TDPresetProperties presetProperties = instance.getPresetProperties();

   //Generate event preset attributes   
   JSONObject 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 attribute
    String bundle_id = presetProperties.bundle_id;//name
    String os =  presetProperties.os;//os type,as Android
    String system_language = presetProperties.system_language;//Cell phone system language type
    int screen_width = presetProperties.screen_width;//Screen width
    int screen_height = presetProperties.screen_height;//Screen height
    String device_model = presetProperties.device_model;//Equipment Model
    String device_id = presetProperties.device_id;//Unique Identification of Equipment
    String carrier = presetProperties.carrier;//Mobile SIM Card Operator Information, Dual Card Dual Standby, Master Card Operator Information
    String manufacture = presetProperties.manufacture;//Mobile phone manufacturers such as HuaWei
    String network_type = presetProperties.network_type;//Network Type
    String os_version = presetProperties.os_version;//System Version Number
    double zone_offset =presetProperties.zone_offset;//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

From v2. Starting with 6.0, SDK supports reporting three special types of events: First Event, Update Event, and Rewrite Event. These three events need to be used in conjunction with TA System 2.8 and later versions. Since special events only apply in certain scenarios, use them to report data with the help of several technological customer successes and analysts.

# 8.1 First Event

The first event refers to the ID of a device or other dimension, which will only be recorded once. For example, in some scenarios, you may want to record the first event on a device, so you can report the data with the first event.

// Example: report the first equipment event, assuming that the event name is DEVICE_FIRST
JSONObject properties = new JSONObject();
try {
    properties.put("INT_PROPERTY", 0);
} catch (JSONException e) {
    e.printStackTrace();
}


instance.track(new TDFirstEvent("DEVICE_FIRST", properties));

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:

// Example: report the first event of the user account, assuming that the event name is USER_FIRST
JSONObject properties = new JSONObject();
try {
    properties.put("INT_PROPERTY", 0);
} catch (JSONException e) {
    e.printStackTrace();
}

TDFirstEvent firstEvent = new TDFirstEvent("USER_FIRST", properties);
// Set the user ID to the of the first event FIRST_CHECK_ID
firstEvent.setFirstCheckId("YOUR_ACCOUNT_ID");

instance.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 requirement 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 the updatable event object is created. The TA will determine the data that needs to be updated based on the event name and event ID.

// Example: report an event that can be updated, assuming that the event name is UPDATABLE_EVENT
JSONObject properties = new JSONObject();
try {
    properties.put("status", 3);
    properties.put("price", 100);
} catch (JSONException e) {
    e.printStackTrace();
}

// Event attributes after reporting status is 3, price is 100
mInstance.track(new TDUpdatableEvent("UPDATABLE_EVENT", properties, "test_event_id"));


JSONObject properties_new = new JSONObject();
try {
    properties_new.put("status", 5);
} catch (JSONException e) {
    e.printStackTrace();
}

// After reporting, the event attribute status is updated to 5 and the price remains unchanged
mInstance.track(new TDUpdatableEvent("UPDATABLE_EVENT", properties_new, "test_event_id"));

Updatable events will update the event time of historical data by default using the current time of the device. If you want to specify the event time, you can specify the event time when reporting the updatable event:

TDUpdatableEvent tdEvent = new TDUpdatableEvent("OVERWRITE_EVENT", properties, "test_event_id");

tdEvent.setEventTime(date, timeZone);
mInstance.track(tdEvent);

# 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 will determine the data that needs to be updated based on the event name and event ID.

// Example: report an event that can be rewritten, assuming that the event name is OVERWRITE_EVENT
JSONObject properties = new JSONObject();
try {
    properties.put("status", 3);
    properties.put("price", 100);
} catch (JSONException e) {
    e.printStackTrace();
}

// After reporting, the event attribute status is 3 and the price is 100
mInstance.track(new TDOverWritableEvent("OVERWRITE_EVENT", properties, "test_event_id"));


JSONObject properties_new = new JSONObject();
try {
    properties_new.put("status", 5);
} catch (JSONException e) {
    e.printStackTrace();
}

// After reporting, the event attribute status is updated to 5 and the price attribute is deleted
mInstance.track(new TDOverWritableEvent("OVERWRITE_EVENT", properties_new, "test_event_id"));

Rewritable events will overwrite the event time of historical data by default using the current time of the device. If you want to specify the event time, you can specify the event time when reporting the rewritable event:

TDOverWritableEvent tdEvent = new TDOverWritableEvent("OVERWRITE_EVENT", properties, "test_event_id"

tdEvent.setEventTime(date, timeZone);
mInstance.track(tdEvent);

# IX. Hongmeng OS Compatibility Scheme

Since DevEco does not support AAR packages, two compatible methods are currently available.

**The latest version is: **1.0.0

**The corresponding Android SDK version is: **2.7.6.1

**Updated: **2022-02-08

Download address (opens new window)

Both methods require imported configuration

  • Global profile ta_public_config.json (Configuration when partial collection attributes need to be disabled)
//Configuration Needs to Disable Collection Attributes
{
  "strarray": [
    {
      "name": "TDDisPresetProperties",
      "value": [
       // {
        //  "value": "#fps"
        // }
      ]
    }
  ]
}

Download the latest Har package, put it in the libs directory of the project, and configure it in the build.gradle file

implementation fileTree(dir: 'libs', include: ['*.jar', '*.har'])

获得TDConfig和ThinkingAnalyticsSDK实例

//initialize
TDTracker.initialize(this);
TDConfig config = TDTracker.getConfigInstance(TA_APP_ID, TA_SERVER_URL);
mInstance = TDTracker.sharedInstance(config);
//track test
mInstance.identify("instance_id1");
ThinkingAnalyticsSDK.enableTrackLog(true);
mInstance.track("testHarmonyOSEvent");

After obtaining the instance, you can access the doc according to the Android SDK to continue the subsequent process.

# 9.2 Jar Package Introduction

To decompress the jar file in the AAR package of Android SDK directly and put it into libs, the developer needs to obtain the converted Context first as the Context parameter to be transferred into Thinking Analytics SDK and at config. Configure the required permissions in the JSON file.

It should be noted that the Hongmeng SDK does not contain the Application class for android, so you need to import android.jar.

  • Convert Context
//Direct acquisition
((Application)(HarmonyApplication.getInstance())).getApplicationContext();
//Reflection acquisition
try {
    Class HarmonyApplicationClazz = Class.forName("ohos.abilityshell.HarmonyApplication");
    Method localMethod = HarmonyApplicationClazz.getMethod("getInstance");
    localMethod.setAccessible(true);
    application = (Application) localMethod.invoke(null);
} catch (Exception e) {
    e.printStackTrace();
}
  • Configure basic network permissions
"module": {
    ......
    "reqPermissions": [{
      "name": "ohos.permission.INTERNET",
    },{
      "name": "ohos.permission.GET_NETWORK_INFO",
    }
    ]
    ......
}

# ChangeLog

# v2.7.6.1 2022/02/07

  • Update the logic for traceless burial points
  • Fix some known problems

# v2.7.5 2022/01/17

  • New Preset Attributes#install_time/#app_version/#simulator/#ram/#disk/#fps/#start_reason
  • Timed event property increased by #backgroud_duration
  • Added SDK configuration file to control preset property switch
  • Added automatic capture event callback
  • Partial code logic optimization

# v2.7.4 2021/12/17

  • Fix some known issues
  • Code structure optimization

# v2.7.3 2021/10/22

  • Add field instance name to identify the instance
  • Add ability to automatically capture event custom attributes
  • Code optimization

# v2.7.1 2021/08/20

  • Adapt to HarmonyOS
  • Optimize app_ End Event Acquisition Logic
  • Code optimization

# v2.7.0 2021/06/16

  • Support preset attribute acquisition
  • Support direct data reporting in child processes in multi-process business scenarios
  • Code optimization

# v2.6.3 2021/03/15

  • Adapt to Android 11
  • Adapt Target 30
  • Optimizing network signal acquisition logic
  • Add #bundle_id preset attribute (application package name or process name)

# v2.6.2 2020/10/29

  • Optimize install, start event reporting logic
  • Optimize data transfer format
  • Default network reporting policy adjusted to 2G/3G/4G/5G/WIFI
  • Optimize the problem of OOM exception in a large number of log outputs

# v2.6.0 2020/08/24

  • Support for first-time events, allowing custom ID verification to be passed in
  • Supports updatable, rewritable events

# v2.5.6 2020/06/28

  • Optimization code: Avoid null pointer exceptions when turning on automatic collection in extreme cases

# v2.5.5 2020/06/22

  • Fix the problem that delayed initialization caused the first startup event not to be collected in some cases
  • Add preset property #system_language
  • Optimize some preset attribute value logic, do not pass when there is no value
  • Optimize partial code and log printing

# v2.5.4 2020/05/19

  • Add interface for Unity 2018.04 adaptation

# v2.5.3 2020/05/14

  • Adapt TA background version 2.7 shielding event configuration interface
  • Adjust the DEBUG mode to remove the client side exception throwing logic
  • QuitSafelyService is turned off by default

# v2.5.2 2020/04/29

  • Fix the problem of time type formatting in user feature.

# v2.5.1 2020/04/14

  • Fix the bug reported by the event in DEBUG mode.

# v2.5.0 2020/04/03

  • Support time calibration function of client SDK
  • Added user feature interface for specified time

# v2.4.3 2020/03/06

  • Optimize startup events to ensure that installation events occur before startup events in the case of delayed initialization

# v2.4.2 2020/03/06

  • Resolved inaccuracy when initializing the SDK before the first activity display ta_app_start

# v2.4.1 2020/03/04

  • Solve the problem of incorrect judgment before and after initializing the SDK after the first activity stops

# v2.4.0 2020/02/10

  • Supports JSONArray types
  • Support user_append interface
  • Remove the client attribute format check

# v2.3.1 2020/01/07

  • Support setting the default time zone of data

# v2.3.0 2019/12/31

  • Support Debug mode: need to be opened together with the background Debug device whitelist (v2.5 version starts to support)
  • H5 and origin SDK open support multiple instances
  • Optimize SDK configuration: add global settings; report policy allows configuration for different projects; support sending data to multiple groups
  • Support for Self-sign Certificates: Allow incoming SSLSocketFactory custom authentication process
  • Other optimizations:
    • Optimize safe exit logic to avoid ANR
    • Remove length restrictions on data of type string

# v2.2.2 2019/11/04

  • Fix exit exception when API level is less than 18 (Android 4.3)

# v2.2.0 2019/10/22

  • Support to reset user feature interface user_unset
  • Added trackinterface overload, support to upload event data according to the specified time zone
  • Added preset attritbute #zone_offsetin hours. By default, the offset of the local time zone is reported to the server level, which is affected by daylight saving time. The following formula is met:
utc_time + #zone_offset = #event_time

# v2.1.0 2019/08/31

  • Supports lightweight instances to facilitate reporting of passive events and other requirements
  • Added enableTrackinginterface, which can turn on or off the instance reporting function
  • Added optOutTracking/ optInTrackinginterface
  • Optimize reporting logic, improve reporting frequency and timeliness
  • Other minor improvements

# v2.0.1 2019/07/12

  • Support H5 and automatic collection of events Add APP installation events

# v2.0.0 2019/07/10

  • Refactoring automatic acquisition logic (need to be compiled with version 2.0 plug-in):
    • Removing third-party library dependencies from the SDK
    • Fragmentbrowsing events no longer need to inherit BaseFragment, annotated
    • Added TimePicker, DatePickerand other controls click event collection
  • Add getDeviceId ()interface
  • Automatic collection of events Add APP installation events
  • Optimized property detection logic: When data of string type exceeds 2048 bytes, it will be automatically truncated and uploaded
  • Optimized log printing for easier event reporting testing during the integration phase
  • Additional code optimizations for SDK stability and operational efficiency
  • minSdkVersion up to 14.

# v1.3.0 2019/06/18

  • Add multiple APPID instance function
  • Added dynamic public attribute feature
  • Automatically collect events Add APP crash events
  • Improved stability: adapting to Android Q, removing unnecessary permission applications, optimizing operator acquisition logic, supporting 5G, etc

# v1.2.0 2019/05/23

  • Support H5 and APP to get through
  • Support for androidx (with auto capture plugin after 1.2.0)
  • Optimize some code logic

# v1.1.7 2019/01/08

  • Added Log print function for reporting data