1. User association

The purpose of user association is to uniquely identify users and improve the accuracy of user behavior analysis. At present, we provide simple user association and global user association to support different business scenarios.

2. User attribute

  • For the difference between event properties and user properties, seedata model
  • For naming restrictions on user attributes, seedata format

2.1. Set user properties

The profileSet() method can set user attributes. When the same key is set multiple times, the value value will be overwritten and replaced.

SensorsDataAPI.sharedInstance().profileSet("Adsource", "userSource");
CODE

2.2. Records the user properties that were set for the first time

We can use properties that are only valid when first setprofileSetOnce() record these properties. Different from profileSet() method, if the set user property already exists, the record is ignored without overwriting existing data, and is automatically created if the property does not exist. Therefore,profileSetOnce() is applicable to setting the first activation time and first registration time. For example:

try { JSONObject properties = new JSONObject(); properties.put("AdSource", "XXX Store"); // 设定用户渠道为,"developer@sensorsdata.cn" 的 "AdSource" 属性值为 "XXX Store" SensorsDataAPI.sharedInstance().profileSetOnce(properties); JSONObject newProperties = new JSONObject(); newProperties.put("AdSource", "Email"); // 再次设定用户渠道,设定无效,"developer@sensorsdata.cn" 的 "AdSource" 属性值仍然是 "XXX Store" SensorsDataAPI.sharedInstance().profileSetOnce(newProperties); } catch (JSONException e) { e.printStackTrace(); }
CODE

2.3. Attributes of a numeric type

For numeric user properties, you can useprofileIncrement() add the property values. It is often used to record attributes such as the number of user payments, payment amount, and points. For example:

// 将用户游戏次数属性增加一次 SensorsDataAPI.sharedInstance().profileIncrement("GamePlayed", 1); // 增加用户付费次数和积分 Map<String, Number> properties = new HashMap<String, Number>(); properties.put("UserPaid", 1); properties.put("PointEarned", 12.5); SensorsDataAPI.sharedInstance().profileIncrement(properties);
CODE

2.4. Properties of a list type

For the user's favorite movies, restaurants reviewed by the user and other attributes, you can record the column phenotype attributes, such as:

Set<String> movies = new HashSet<String>(); movies.add("Sicario"); movies.add("Love Letter"); // 设定用户观影列表属性,设定后属性 "Movies" 为: ["Sicario", "Love Letter"] SensorsDataAPI.sharedInstance().profileAppend("Movies", movies);
CODE

Note that the element in the column phenotype attribute must be String type. See column phenotypic restrictionsdata format.

2.5. Attribute cancellation

If you need to cancel a user property that has been set, you can call profileUnset() to cancel:

SensorsDataAPI.sharedInstance().profileUnset("age");
CODE

3. Tracking event acquisition

After SDK initialization is complete, you can bury data through the following interface.

3.1. Code tracking trace event

After SDK initialization, you can use track()method track user behavior events and adds custom properties to events.

try { JSONObject properties = new JSONObject(); properties.put("ProductID", 123456); // 设置商品 ID properties.put("ProductCatalog", "Laptop Computer"); // 设置商品类别 SensorsDataAPI.sharedInstance().track("BuyProduct", properties); } catch (JSONException e) { e.printStackTrace(); }
CODE

For the format specifications of event names and event attributes, seedata format.

3.2. Tracking event collection duration attribute

You can count the duration of an event with a timer. First, it is called at the beginning of the event(v1.10.6 and later version) trackTimerStart("Event") , This method does not actually send the event; At the end of the event, calltrackTimerEnd("Event", properties),SDK will trigger "Event" event, and automatically records the event duration in the event properties "$event_duration" . For example, record the time users spend browsing product pages:

// 进入商品页面 // 调用 trackTimerStart("ViewProduct") 标记事件启动时间 SensorsDataAPI.sharedInstance().trackTimerStart("ViewProduct"); // ... 用户浏览商品 // 离开商品页 try { // 在属性中记录商品 ID JSONObject properties = new JSONObject(); properties.put("product_id", PRODUCT_ID); // 调用 track,记录 ViewProduct 事件,并在属性 event_duration 中记录用户浏览商品的时间 SensorsDataAPI.sharedInstance().trackTimerEnd("ViewProduct", properties); } catch (JSONException e) { e.printStackTrace(); }
CODE

Multiple call trackTimerStart("Event") , event The start time of "Event" is based on the last call.Note It is important to ensure that the trackTimerStart and trackTimerEnd interfaces are used together. Calling trackTimerEnd multiple times will trigger an eternally-buried event.

From v3.1.5 version, Statistical event duration supports pause and recovery by callingtrackTimerPause(String eventName) and trackTimerResume(String eventName) to pause and resume, respectively. Called if the recorded duration event needs to be clearedclearTrackTimer() interface.

3.2.1. Statistics on the duration of intersections of events with the same name

By default, the duration of the statistics is identified by the event name. The same event name will automatically match start-end. If two events with the same name cross part in time, an incorrect match will be caused. In order to solve this problem, starting from version 3.2.11, the SDK supports the duration statistics of events with the same name, and developers need to save the return value of trackTimerStart() for subsequent targeted pause, resume or stop.

Note It is important to ensure that the trackTimerStart and trackTimerEnd interfaces are used together. Calling trackTimerEnd multiple times will trigger an eternally-buried event. Use v6.5.5 or later for this function. Abnormal events may occur when the earlier version is not used in pairs.

// 开始第一个事件计时 String timer1 = SensorsDataAPI.sharedInstance().trackTimerStart("testTimer"); // 开始第二个事件计时 String timer2 = SensorsDataAPI.sharedInstance().trackTimerStart("testTimer"); //如果需要暂停第一个事件计时 SensorsDataAPI.sharedInstance().trackTimerPause(timer1); //如果需要恢复第一个事件计时 SensorsDataAPI.sharedInstance().trackTimerResume(timer1); // 结束第一个事件计时 SensorsDataAPI.sharedInstance().trackTimerEnd(timer1); // 结束第二个事件计时 SensorsDataAPI.sharedInstance().trackTimerEnd(timer2);
CODE

3.3. Collects page view duration

Version requirements

  • Android  SDK v6.6.6 and above version
  • Android plugin v3.5.2 and above version

The SDK supports automatic collection of page view duration by sending a page exit event ($AppPageLeave) when you leave the pageSAConfigOptions  instance enableTrackPageLeave(boolean, boolean) property enable Page viewing duration Event Collection:

  • The first parameter indicates whether the collection Activity page leaves the event collection
  • The second parameter indicates whether the Fragment page leaves the event collection
// 传入 true, true 代表开启 Activity 和 Fragment 页面离开事件采集 saConfigOptions.enableTrackPageLeave(true, true); // 若想只采集 Activity,单独关闭 fragment 页面离开采集 saConfigOptions.enableTrackPageLeave(true, false)
CODE

If you want to ignore the view duration collection for a specified page, run the ignorePageLeave(List< Class>) To ignore it.

configOptions.ignorePageLeave(Arrays.asList(TestMainActivity.class, FragmentActivity.class));
CODE

If page view duration collection is enabled, the $AppPageLeave event is collected and the page view duration is recorded in the event.

For vThe page browsing duration function of the version between 6.4.3 and v6.6.5 cannot be used together with the disableSDK interface. Therefore, the function must be upgraded to v6.6.6 or later.

Disable the collection version of the Fragment separately v6.2.6.

3.4. Item metadata report

3.4.1. Set item properties

Set an item directly and overwrite it if it already exists. In addition to the item ID and the type the item belongs to, other item properties need to be defined in Properties. In item attributes, the constraints on the attribute name and attribute value are the same as those on event attributes. For details, please refer todata format.

// 为物品类型为 itemType 且物品 ID 为 itemId 的物品,设置物品属性 properties SensorsDataAPI.sharedInstance().itemSet(String itemType, String itemId, JSONObject properties);
CODE

3.4.2. Delete item attributes

If the item cannot be recommended and needs to go offline, just delete it, or ignore it if it does not exist. Other than the item ID and type of the item, no other item attributes are parsed.

// 删除物品,类型为 itemType,ID 为 itemId SensorsDataAPI.sharedInstance().itemDelete(String itemType, String itemId);
CODE

4. Event attribute

When tracking buried events, you can define buried event attributes as required. At present, the SDK provides public attributes for adding attributes to each buried point event, and public attributes are divided into static public attributes and dynamic public attributes. Static public properties are used to set the properties with low update frequency, and dynamic public properties are used to set the properties with high update frequency. When a property of the same Key appears in the same event, the SDK overrides the priority: preset property < Static public attribute < Dynamic public attribute < Custom properties.

4.1. Get preset properties

v1.8.17 and later versions can call the getPresetProperties() method to get preset properties. If the embedded point on the server requires some preset properties on the App, you can obtain the preset properties on the App in this method and send them to the server.

//获取预置属性 JSONObject presetProperties=SensorsDataAPI.sharedInstance().getPresetProperties();
CODE

4.2. Static public attribute

Static public properties are properties that need to be added for all events. After initializing the SDK, A property can be registered as a public property with registerSuperProperties() . The setting method is as follows:

// 将应用名称作为事件公共属性,后续所有 track 类型的事件都会自动带上 "AppName" 属性 try { JSONObject properties = new JSONObject(); properties.put("AppName", getAppName(this)); SensorsDataAPI.sharedInstance().registerSuperProperties(properties); } catch (JSONException e) { e.printStackTrace(); }
CODE

Can use SensorsDataAPI. SharedInstance (.) getSuperProperties () set to obtain the public properties.

  • A registered static public property can be deleted by using the unregisterSuperProperty(String key) method.
  • For the delayed initialization scenario, the triggered $AppStart event will not be able to carry static public attributes and will need to useProperties pluginization in Advanced Features Sets properties in initialization.

4.3. Set dynamic public properties

Dynamic public properties are dynamic properties that need to be added for all events. Android SDK v2.0.1 and later version can use registerDynamicSuperProperties() method set dynamic public properties. After setting, SDK will automatically obtain the buried points every time getDynamicSuperProperties() attribute in the command is added to the triggered event.

// 初始化 SDK 后,设置动态公共属性 SensorsDataAPI.sharedInstance().registerDynamicSuperProperties(new SensorsDataDynamicSuperProperties() { @Override public JSONObject getDynamicSuperProperties() { try { // 比如 isLogin() 是用于获取用户当前的登录状态,SDK 会自动获取 getDynamicSuperProperties 中的属性添加到触发的事件中。 boolean bool = isLogin(); return new JSONObject().put("isLogin",bool); } catch (Exception e) { e.printStackTrace(); } return null; } });
CODE

Call registerDynamicSuperProperties() method to set dynamic public properties, can't use unregisterSuperProperty() method to delete.

5. Data storage and sending

You need more fine-grained control over your analytics and can set up the data acquisition function with the following options.

5.1. Data flush report

Each call track()login()profileSet() method. The SDK will save the buried event in the database and check the following conditions to determine whether to upload data to the server:

  1. Whether WIFI/2G/3G/4G/5G network conditions
  2. Whether one of the sending conditions is met:
    1. Whether the time interval between the last sending is greater than flushInterval
    2. Whether the number of local cache logs is greater than flushBulkSize
    3. Event type as login() method triggers $SignUp event

The default flushBulkSize is 100, default flushInterval is 15 seconds. After the conditions are met, the SDK will gzip the data and send it to the SDK in batches.

If the pursuit of timeliness of data collection, you can callflush() method, force data to be sent to divine analytics, for example:

// 记录用户登录事件 SensorsDataAPI.sharedInstance().track("UserLogin"); // 强制发送数据 SensorsDataAPI.sharedInstance().flush();
CODE

The SDK is called when the App enters the background state or listens to the network switch flush() method, send cached data to Sensors Analytics.

5.2. Set the network policy for sending data

By default, the SDK will attempt to synchronize data on WIFI/3G/4G/5G networks.v1.7.2and later versions support network policies that can be customized to synchronize data. passSAConfigOptions.setNetworkTypePolicy() at initialization or SensorsDataAPI.setFlushNetworkPolicy() method to specify a network policy for sending data. For example:

//网络模式选项 //SensorsDataAPI.NetworkType.TYPE_2G 2G网络下发送数据 //SensorsDataAPI.NetworkType.TYPE_3G 3G网络下发送数据 //SensorsDataAPI.NetworkType.TYPE_4G 4G网络下发送数据 //SensorsDataAPI.NetworkType.TYPE_5G 5G网络下发送数据 //SensorsDataAPI.NetworkType.TYPE_WIFI WIFI网络下发送数据 //SensorsDataAPI.NetworkType.TYPE_ALL 2G/3G/4G/5G/WIFI网络下发送数据 //SensorsDataAPI.NetworkType.TYPE_NONE 所有网络下都不发送数据 //指定只在 3G/4G/WIFI 条件下发送数据。 SensorsDataAPI.sharedInstance().setFlushNetworkPolicy(SensorsDataAPI.NetworkType.TYPE_3G|SensorsDataAPI.NetworkType.TYPE_4G|SensorsDataAPI.NetworkType.TYPE_WIFI);
CODE

5.3. Example Set the upper limit of local cache

By default, the upper limit of cached data in the SDK local database is 32MB.v1.7.4 and later versions are supported setMaxCacheSize() method to set the upper limit of cached data. Parameter unit byte.

SAConfigOptions saConfigOptions = new SAConfigOptions(SA_SERVER_URL); //在初始化时,利用 SAConfigOptions 设置本地数据缓存上限值为16MB saConfigOptions.setMaxCacheSize(16 * 1024 * 1024);
CODE

v3.1.0 and previous versions, set the cache mode: 

//设置本地数据缓存上限值为16MB SensorsDataAPI.sharedInstance().setMaxCacheSize(16 * 1024 * 1024);
CODE


When the storage quantity reaches the upper limit, old data is discarded and the latest data is retained

5.4. Set the event sending interval

If tracking events are triggered continuously, the interval for sending buried point data is 15s by default. The SDK provides interface SAConfigOptions. SetFlushInterval (int) in the initialization time(v3.1.0 and above supported) and SensorsDataAPI. SetFlushInterval (int) in the initialization for custom setting event buried after sending interval. The unit is milliseconds. The minimum value is 5s.

SAConfigOptions saConfigOptions = new SAConfigOptions(SA_SERVER_URL); //在初始化时,利用 SAConfigOptions 设置相关参数 // 设置每 30 秒发送一次 saConfigOptions.setFlushInterval(30000);
CODE

It also supports <meta-data> settings.

<application> <meta-data android:name="com.sensorsdata.analytics.android.FlushInterval" android:value="30000" /> </application>
CODE

5.5. Set the number of events cached

The default value of the local buried data cache is 100. When a buried point event is triggered, if the number of buried point events in the local cache is not less than the specified cache number, the buried point data is immediately sent without waiting for an interval of 15s.

The SDK provides interface SAConfigOptions. SetFlushBulkSize (int) in the initialization time (v3.1.0 And above) and SensorsDataAPI setFlushBulkSize (int) in the initialization for custom setting event buried after sending interval. The minimum value is 50.

SAConfigOptions saConfigOptions = new SAConfigOptions(SA_SERVER_URL); //在初始化时,利用 SAConfigOptions 设置相关参数 // 设置缓存大小 saConfigOptions.setFlushBulkSize(100);
CODE

It also supports <meta-data> settings.

<application> <meta-data android:name="com.sensorsdata.analytics.android.FlushBulkSize" android:value="100" /> </application>
CODE

5.6. Clear local cache events

v3.1.5 and later version can use deleteAll() method to delete all events stored locally in the App.

Do not call this method unless specifically requested.

//删除 App 本地存储的所有事件 SensorsDataAPI.sharedInstance().deleteAll();
CODE

5.7. Set from the visa document

v3.1.2 及以后的版本可以通过 setSSLSocketFactory() 方法设置自签证书,设置自签证书后,SDK 内所有的 HTTPS 请求会进行此接口设置的证书校验。以 DER 格式的证书为例:

try { //构建 SSLSocketFactory 实例 SSLSocketFactory sslSocketFactory ; CertificateFactory cf = CertificateFactory.getInstance("X.509"); // 其中 R.raw.ca 是您这边自签证书的公钥 InputStream in = getResources().openRawResource(R.raw.ca); Certificate ca = cf.generateCertificate(in); try { in.close(); } catch (Exception e) { e.printStackTrace(); } KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, null); keystore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keystore); // Create an SSLContext that uses our TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); sslSocketFactory = sslContext.getSocketFactory();     //将实例传入神策 SAConfigOptions configOptions = new SAConfigOptions(SA_SERVER_URL); configOptions.setAutoTrackEventType(SensorsAnalyticsAutoTrackEventType.APP_START | SensorsAnalyticsAutoTrackEventType.APP_END | SensorsAnalyticsAutoTrackEventType.APP_VIEW_SCREEN | SensorsAnalyticsAutoTrackEventType.APP_CLICK) .setSSLSocketFactory(sslSocketFactory) SensorsDataAPI.startWithConfigOptions(this, configOptions); } catch (Exception e) { e.printStackTrace(); }
CODE

You can read more about SSL Android Usage document.

6. SDK encipher

This section describes the buried data encryption and cache data encryption functions provided by the SDK. The buried data encryption function encrypts the collected buried data and stores it in ciphertext in the SQLite database. Cache data encryption refers to encrypting information such as flag bits stored in the SDK, including SharedPreferences and File information.

6.1. Cache data encryption

The SDK encrypts the contents in the cache. The version required is Android SDKv6.2.0 and above, at the same time, the developer should take the initiative to open.

The AES encryption mode is used by default in the SDK. AES 128 is offset by 16 bits. When the SDK is initialized, the registerStorePlugin interface is called to register the preset encryption plug-in. Refer to the following code to enable encryption:

SAConfigOptions configOptions = new SAConfigOptions("数据接收地址"); //注册 MuPlugin 插件 configOptions.registerStorePlugin(new SAEncryptStorePlugin(this)); SensorsDataAPI.startWithConfigOptions(this, configOptions);
CODE

If there are requirements on the encryption method, the default encryption can not meet the requirements, you can realize custom encryption, custom encryption method can consult SDK students on duty.

Once compliant encryption or custom encryption is implemented, Encrypted data cannot be restored to unencrypted data.

6.2. Tracking data encryption

In order to enhance the security of buried data, Shenze Analysis supports the encryption of buried data, and stores and sends the data in ciphertext.

Note

This function requires the cooperation of the server, you can contact the customer success/project manager to help open the server decryption function. The default key is RSA. You can specify an EC key.

Note: When you switch to non-encrypted mode after encryption is enabled, the back-end of the local encrypted data cannot be parsed into the database.

6.2.1. SDK Enables Tracking point encryption

For v4.2.0+ version SDK. Before initialization, perform the following configurations to enable the buried point encryption function of the SDK. Buried point encryption encrypts buried point data, stores it, and then reports it.

// 开启加密 configOptions.enableEncrypt(true);
CODE

For The SDK version v4.4.0+ starts to support EC algorithm encryption. In useenableEncrypt() Enable encryption and add the following dependencies to switch to the EC algorithm:

dependencies { // 添加 EC 算法库依赖 implementation 'com.sensorsdata.provider:SensorsAnalyticsProvider:0.0.3' }
CODE

Note

The SensorsAnalyticsProvider encapsulates the Android OS v1.58.0.0 EC algorithm library (you can also integrate this library from GitHub), the size of the library is about 5MB. At the same time, the warehouse contains many methods. For large projects, the number of methods may exceed 64KSee the official Android configuration documentenable multiDexEnabled configuration.

6.2.2. Authentication of encryption keys

Before using this function, ensure that the Scheme of the current project is configured in your App. For details, seeConfigure Scheme

In the Sensors Analytics platform, enter the key management function, enter the path: "More" → "Basic Settings" → "Data Access" → "Key Management"

Click "Key Management" button to enter the key management page

Click the QR code icon of the corresponding key , and scan the QR code with the browser to open the App for key verification.

  • If the verification is consistent, the App prompts "Key verification passed, the selected key is the same as the App key".
  • If the authentication is inconsistent, the App displays the message "The key authentication fails because the selected key is different from the App key." Selected key version :v1, App key version :v2"
  • If the local key is empty, the App displays the message "Key authentication failed, App key is empty."
  • If the scan key is empty, the App prompts "Key verification fails, the selected key is invalid".

7. Full Tracking

Full Tracking refers to $AppStart (App start), $AppEnd (App exit), $AppViewScreen (page view) and $AppClick (control click) four kinds of events. For App startup and exit, Sensors SDK in order to deal with multi-process, strong killing and other scenarios, inv2.0.3 The version added a 30-second session mechanism. The exit event will be triggered only when the user exits the App to the background for 30 seconds, and the startup event will be triggered only when the App is started again. If the user opens the App within 30 seconds, there is no corresponding exit event and startup event. In addition, if the process is not killed within 30 seconds of exiting the App to the background, then the exit event will be triggered and attempt to report, if the process is killed, then the exit event will be reissued at the next startup. Therefore, when viewing the data, there are generally fewer exit events than startup events.

7.1. Open the full tracking

The SDK can automatically collect some user behaviors, such as App startup, exit, page browsing, and control clicks. When initializing the SDK, usesetAutoTrackEventType() method you can set the type of full burial point to be enabled:

// 可根据需求,自由组合 saConfigOptions.setAutoTrackEventType(SensorsAnalyticsAutoTrackEventType.APP_CLICK| SensorsAnalyticsAutoTrackEventType.APP_START| SensorsAnalyticsAutoTrackEventType.APP_END| SensorsAnalyticsAutoTrackEventType.APP_VIEW_SCREEN);
CODE

Full tracking event collection for App startup and App exit requires API 14 (Android 4.0) as the minimum system version.

7.1.1. Example Enable the Fragment page browsing event

Starting from v1.7.10 , Use trackFragmentAppViewScreen() method can enable the automatic collection of all Fragment page browsing events:

// 初始化 SDK 之后,开启自动采集 Fragment 页面浏览事件 SensorsDataAPI.sharedInstance().trackFragmentAppViewScreen();
CODE

After enabling the Fragment page browsing event, useenableAutoTrackFragment() method specify that only certain Fragment pages are collected:

// 只采集 HomeFragment 页面的浏览事件 SensorsDataAPI.sharedInstance().enableAutoTrackFragment(HomeFragment.class);
CODE

7.2. Full tracking event acquisition control

For App page browsing and App element clicking in the full buried point, after the full buried point is enabled, the SDK supports ignoring the collection of some pages or controls through configuration, and provides a method to manually trigger the full buried point event. Some special buried point events still need to call additional methods to open the collection after opening the buried point.

7.2.1. Ignore all buried events

Starting from v2.0.0, usedisableAutoTrack(AutoTrackEventType) 和 disableAutoTrack(List<AutoTrackEventType>) method can ignore fully buried events of a specified type. At the same time, the ignored buried point event can use enableAutoTrack(List<AutoTrackEventType>) methods to resumed collection.

// 忽略点击事件 SensorsDataAPI.sharedInstance().disableAutoTrack(SensorsDataAPI.AutoTrackEventType.APP_CLICK);
CODE

7.2.2. Collects the page browsing event of the specified Fragment

By default, the SDK collects all Fragment page view events. Fromv3.2.6, use enableAutoTrackFragment(Class<?> fragment) and enableAutoTrackFragments(List<Class<?>> fragmentsList) method to collect the specified Fragment page browsing event.

// 采集指定 Fragment SensorsDataAPI.sharedInstance().enableAutoTrackFragment(Class<?> fragment);
CODE

Note

The enableAutoTrackFragment() method is used to collect the specified Fragment page, and the ignoreAutoTrackFragment() method is used to ignore the specified Fragment page. If both Settings exist at the same time, set enableAutoTrackFragment() and ignoreAutoTrackFragment().

7.2.3. Ignore Fragment page browsing events

Starting from v3.2.6 , use ignoreAutoTrackFragment() method can ignore page browsing events for some Fragment pages:

// 忽略单个 Fragment SensorsDataAPI.sharedInstance().ignoreAutoTrackFragment(Class<?> fragment); // 忽略多个 Fragment SensorsDataAPI.sharedInstance().ignoreAutoTrackFragments(List<Class<?>> fragmentList);
CODE

Starting from v3.2.6 , use resumeIgnoredAutoTrackFragment() method can recover page browsing events for ignored Fragment pages:

// 恢复单个 Fragment SensorsDataAPI.sharedInstance().resumeIgnoredAutoTrackFragment(Class<?> fragment); // 恢复多个 Fragment SensorsDataAPI.sharedInstance().resumeIgnoredAutoTrackFragments(List<Class<?>> fragmentList);
CODE

Attention

The enableAutoTrackFragment() method is used to collect data from specified Fragment pages, while the ignoreAutoTrackFragment() method is used to ignore specified Fragment pages. When both methods are set, the information set by enableAutoTrackFragment() will take effect, and the information set by ignoreAutoTrackFragment() will not take effect.

7.2.4. Ignore Full-Track Events in Activity

Use ignoreAutoTrackActivity()method can ignore App click events and App page browse events (including owning fragments) for one or more activities. It can also use resumeAutoTrackActivities(List<Class<?>>) and resumeAutoTrackActivity(Class<?>) method to recover the ignored page.

// 忽略单个 Activity SensorsDataAPI.sharedInstance().ignoreAutoTrackActivity(Class<?> activity); // 忽略多个 Activity SensorsDataAPI.sharedInstance().ignoreAutoTrackActivities(List<Class<?>> activitiesList);
CODE

7.2.5. Ignore Click Events of a View

The ignoreView() method can be used to ignore App click events of a specific View object:

SensorsDataAPI.sharedInstance().ignoreView(View view);
CODE

7.2.6. Ignore Click Events of a Type of View

The ignoreViewType() method can be used to ignore App click events of a certain type of control and its subtypes:

SensorsDataAPI.sharedInstance().ignoreViewType(Class viewType);
CODE

viewType can be a common Android control type or a custom type, such as:CheckBox、RadioButton、ToggleButton、Switch、Button、ImageButton、CheckedTextView、TextView、ImageView、RatingBar、SeekBar、Spinner、ListView、ExpandableListView、RecyclerView、TabHost、TabLayout、MenuItem、Dialog、GridView.

7.2.7. Ignore Page View Events

The @SensorsDataIgnoreTrackAppViewScreen annotation can be used to ignore App page view events of a specific Activity (including associated Fragments) or Fragment. For example, ignore the page view events of DemoActivity:

// 忽略 DemoActivity 的页面浏览事件 @SensorsDataIgnoreTrackAppViewScreen public class DemoActivity extends AppCompatActivity { }
CODE

7.3. Triggering Full-Track Events Manually

Triggering Full-Track Events manually means that developers manually call the interface provided by the SDK to trigger App page view and App element click events. The difference between manually triggered Full-Track Events and automatically triggered Full-Track Events by the SDK is that the value of lib_method in manually triggered Full-Track Events is "code", while the value of automatically triggered Full-Track Events by the SDK is "autoTrack". Note that it is recommended not to mix this function with Full-Track to prevent event duplication.

7.3.1. Manually Triggering Page View Events

Starting from v1.7.9, the trackViewScreen() method can be used to manually trigger App page view events, and this interface is not limited by ignore conditions.

//触发 Activity 的浏览页面事件 SensorsDataAPI.sharedInstance().trackViewScreen(Activity activity); //触发 Fragment 的浏览页面事件 SensorsDataAPI.sharedInstance().trackViewScreen(Fragment fragment);
CODE

7.3.2. Manually Triggering Click Events of a Control

Starting from v3.2.6, the trackViewAppClick() method can be used to manually trigger App click events, and this interface is not limited by ignore conditions.

//触发该 View 的点击事件 SensorsDataAPI.sharedInstance().trackViewAppClick(View view); //触发该 View 的点击事件,并加上自定义属性 SensorsDataAPI.sharedInstance().trackViewAppClick(View view, JSONObject properties);
CODE

7.3.3. Ignore Page Leave Events of Activity/Fragment

//忽略 API ignorePageLeave(List<Class<?>> ignoreList) 
CODE

Ignore Activity collection without affecting the collection of page stay time in associated Fragments.

7.3.4. Click events set through the onClick attribute

Through the layout file android:onClick The App click event cannot be triggered automatically when the click callback method of the property configuration is executed. At this time can give android:onClick Attribute corresponding to the method add @SensorsDataTrackViewOnClick Annotation, so that the SDK can automatically trigger the App click event when the method is executed. For example:

Layout file:

<Button 	android:onClick="buttonOnClick"/>
CODE

Processing function:

import com.sensorsdata.analytics.android.sdk.SensorsDataTrackViewOnClick; @SensorsDataTrackViewOnClick public void buttonOnClick(View v) {}
CODE

7.3.5. An event is automatically triggered when the method is executed

Use @SensorsDataTrackEvent annotations can do: when onepublic method is executed, an event is automatically triggered. For example:

// eventName 代表事件名,properties 代表事件属性 @SensorsDataTrackEvent(eventName = "someEventName", properties = "{"provider":"神策数据","number":100,"isLogin":true}") public void someMethod() {}
CODE

7.4. Full tracking event attribute added

If you encounter the following problems when using the fully buried App page browsing and App element clicking:

· You need to add custom properties to App click events or App page browse events · Some preset attributes have not been collected, such as $element_content attribute for picture button and $title attribute for page · The preset attributes collected do not meet business requirements

In this case, you can use the methods provided by the SDK to modify or supplement the default attribute value.

7.4.1. Page set custom properties

Use ScreenAutoTracker interface can set custom properties for the page or modify the values of preset properties. The class to implement the interface must be the Activity or Fragment class corresponding to the page:

public interface ScreenAutoTracker { 	String getScreenUrl(); 	JSONObject getTrackProperties() throws JSONException; }
CODE

After the class corresponding to the page implements the interface, the SDK will trigger the App page browsing or App clickgetTrackProperties() the properties in the return value added to the event properties of the eventgetScreenUrl() the returned value recorded to the preset property $url, preset attribute $referrer the value is the last time the App page browsing was triggered$url.

If you want to override the preset properties of other fully-buried sites, you can add the corresponding property name and property value to the objectgetTrackProperties() returned JSONObject.

Note

In the JSONObject returned by the getTrackProperties() method of the ScreenAutoTracker interface, You can set the $title and $screen_name properties to replace the SDK's default collection Activity and Fragment class page title and page name.

7.4.2. Set page title $title

Activity page browsing event $title Read the Activity title property as follows: First read activity.getTitle(). If actionBar is used and actionbar.getTitle () is not empty, actionbar.getTitle () overwrites activity.getTitle(), If the title is not read in either step, get the android:label attribute of the activity.

If you do not use the ActionBar, you can set the label for the corresponding Activity in the Manifest, so that the content of the $title field will be the set label content:

<activity 	android:label="商品详情页" 	android:name=".DemoActivity" 	android:theme="@style/Theme.AppCompat.Light.NoActionBar" /> ...
CODE

By default, the $title attribute of the Fragment page browsing event is the same as the $title collection rule of the Activity. In SDK 2.0.0 and above, you can use the @SensorsDataFragmentTitle annotation to set the value of the Fragment $title attribute:

@SensorsDataFragmentTitle(title = "HomeFragment") public class HomeFragment extends Fragment { ... }
CODE

7.4.3. Set element ID

By default, the SDK uses android:id as the value of the App click event $element_id attribute, if the element is not set android: id attribute, If the Settings do not meet the requirements, you can override the default element ID using the following method:

// 给 View 对象设置元素 ID SensorsDataAPI.sharedInstance().setViewID(View view, String viewID); // 给 Dialog 对象设置元素 ID SensorsDataAPI.sharedInstance().setViewID(Dialog view, String viewID); // 给 AlertDialog 对象设置元素 ID SensorsDataAPI.sharedInstance().setViewID(AlertDialog view, String viewID);
CODE

NotesetViewID() The priority of the set value is higher than android:id value.

7.4.4. Sets the Activity where the element is located

By default, the SDK will try to get the Activity page where the View element is located, but if it can't, you can try to specify it using the setViewActivity(View, Activity) method.

SensorsDataAPI.sharedInstance().setViewActivity(View view, Activity activity);
CODE

7.4.5. Set the Fragment name of the element

By default, the SDK will try to fetch the Fragment page where the View element resides, but if it cannot be retrieved, you can try to specify the full path name of the Fragment where the View resides using the setViewFragmentName(View, Activity) method. The SDK will reflect the set value to create a Fragment for the $screen_name value.

SensorsDataAPI.sharedInstance().setViewFragmentName(View view, String fragmentName);
CODE

7.4.6. Control to set custom properties

Use setViewProperties() method extend the event properties of the App click event for the specified View object.

SensorsDataAPI.sharedInstance().setViewProperties(View view, JSONObject properties);
CODE

For ExpandableListView,Can also usesetViewProperties() to extend the item corresponding to the View, or through the AdapterSensorsExpandableListViewItemTrackProperties interface to extend event attributes.

package com.sensorsdata.analytics.android.sdk; public interface SensorsExpandableListViewItemTrackProperties { 	/** 	 * 点击 groupPosition、childPosition 处 item 的扩展属性 	 */ 	JSONObject getSensorsChildItemTrackProperties(int groupPosition, int childPosition) throws JSONException; 	/** 	 * 点击 groupPosition 处 item 的扩展属性 	 */ 	JSONObject getSensorsGroupItemTrackProperties(int groupPosition) throws JSONException; }
CODE

For ListViewGridView, the same can also usesetViewProperties() to extend the item corresponding to the View, and through the AdapterSensorsAdapterViewItemTrackProperties interface to extend event attributes.

package com.sensorsdata.analytics.android.sdk; public interface SensorsAdapterViewItemTrackProperties { 	/** 	 * 点击 position 处 item 的扩展属性 	 */ 	JSONObject getSensorsItemTrackProperties(int position) throws JSONException; }
CODE

7.5. Bury all the notes

AnnotationInstructionsExample
@SensorsDataAutoTrackAppViewScreenUrlCustomize the $url property of the $AppViewScreen event with annotations
@SensorsDataAutoTrackAppViewScreenUrl(url = "主页面") public class MainActivity extends Activity { }
CODE


@SensorsDataIgnoreTrackAppClickIgnore all View click events in an Activity or Fragment page with annotations ($AppClick)
@SensorsDataIgnoreTrackAppClick public class MainActivity extends Activity { }
CODE
@SensorsDataIgnoreTrackAppViewScreenUser Segment Ignored Page Browsing Event ($AppViewScreen) through annotation
@SensorsDataIgnoreTrackAppViewScreen public class MainActivity extends Activity { }
CODE
@SensorsDataIgnoreTrackAppViewScreenAndAppClickIgnore Page Browsing Event ($AppViewScreen) and Click Event ($AppClick) of all Views on the page through annotation
@SensorsDataIgnoreTrackAppViewScreenAndAppClick public class MainActivity extends Activity { }
CODE
@SensorsDataIgnoreTrackOnClickIgnore $AppClick Click Event through annotation
@SensorsDataIgnoreTrackOnClick public void onClick(View v) { }
CODE
@SensorsDataTrackEventCollect one event through annotation
@SensorsDataTrackEvent(eventName = "TestEvent", properties = "Json 字符串属性") public void trackEvent() { 	... }
CODE
@SensorsDataTrackViewOnClickCollect $AppClick Click Event through annotation, the premise is that the page cannot be ignored
@SensorsDataTrackViewOnClick public void clickShow(View v) { 	 }
CODE

8. Other functions

8.1. Enable automatic collection of screen orientation

v1.10.1 and later versions can enable the collection of screen orientation properties through the enableTrackScreenOrientation() method, and the screen orientation information is recorded in the $screen_orientation property of the event. Note: After enabling this interface, it will read the sensor information of the phone, so please explain it according to compliance requirements.

SAConfigOptions saConfigOptions = new SAConfigOptions(SA_SERVER_URL); //利用初始化的 SAConfigOptions 对象开启屏幕方向属性的收集 saConfigOptions.enableTrackScreenOrientation(true); SensorsDataAPI.startWithConfigOptions(this, saConfigOptions);
CODE

8.2. Enable automatic collection of location information

v1.10.1 and later versions can set the longitude and latitude information obtained by the third-party location to the SDK through the setGPSLocation() method. After setting it, the longitude and latitude information will be recorded in the $longitude and $latitude properties of the event. Call the clearGPSLocation() method to clear the location information.

//设置经纬度 SensorsDataAPI.sharedInstance().setGPSLocation(latitude,longitude); // 清除位置信息 SensorsDataAPI.sharedInstance().clearGPSLocation();
CODE

8.3. Enable automatic collection of push click events

Version requirements

  • Android SDK v5.4.3 and above, v6.6.5 and above are compatible with JPush 4.6.0 and above
  • Android plugin v3.4.1 and above

Before initializing the SDK, useSAConfigOptions instance enableTrackPush() methods to enable the collection of push click events:

// 传入 true 代表开启推送点击事件自动采集 saConfigOptions.enableTrackPush(true);
CODE

Please refer to the description of this preset event App SDK preset events and preset properties.

  1. The current support includes JPush and JPush vendor channels, Umeng and Umeng vendor channels, and Getui (Getui vendor channels are not supported)
  2. The push collection hooks into the push interface, please implement the relevant interface for push click
    1. JPush &lt; 4.6.0
      1. Self-built channel: Please configure JPushMessageReceiver in AndroidManifest.xml and implement the onNotifyMessageOpened method of JPushMessageReceiver. See details
      2. Vendor channel: uri_activity and uri_action must be configured
    2. JPush &gt;= 4.6.0
      1. Self-built channel/vendor channel: Configure intent or uri_activity and uri_action
      2. No notification jump target address: Please configure JPushMessageReceiver in AndroidManifest.xml and implement the onNotifyMessageOpened method of JPushMessageReceiver. See details
    3. Umeng push
      1. Self-built channel: Please implement UmengNotificationClickHandler class's launchApp、openUrl、openActivity、dealWithCustomAction method See details
      2. Vendor channel: Configure UmengNotifyClickActivity in AndroidManifest.xml and implement the onMessage method of UmengNotifyClickActivity. See details
    4. Getui, please implement the onReceiveMessageData and onNotificationMessageClicked methods in GTIntentService. See details
  3. Version Support
    1. Compatible with JPush SDK versions jpush:3.9.1+ and jcore:2.6.0+, and compatible with JPush-wrapped vendor SDK versions 3.9.1+.
    2. Getui supports 3.2.2.0, Getui core component 3.1.2.0+
    3. Umeng supports 6.3.3+

8.4. Visualized Full Link Tracking

8.4.1. Enable Visualized Full Link Tracking

Version Requirements

  • Sensors Analytics v1.17.2517+
  • Android SDK v4.0.0+

When the SDK is initialized, perform the following configuration to enable the visual buried point:

// 开启可视化全埋点 saConfigOptions.enableVisualizedAutoTrack(true);
JAVA

After the visual bury point is enabled, the function takes effect on all the clicks on the page by default. If you only want to visualize the full bury point on some pages, you can useaddVisualizedAutoTrackActivity() or addVisualizedAutoTrackActivities() method to configure:

//开启某个 Activity 的可视化全埋点 SensorsDataAPI.sharedInstance().addVisualizedAutoTrackActivity(Class<?> activity); //开启多个 Activity 的可视化全埋点 SensorsDataAPI.sharedInstance().addVisualizedAutoTrackActivities(List<Class<?>> activitiesList);
CODE

8.4.2. Visual full tracking custom properties

If you need the Android SDKv6.0.0+ Use visual full tracking to customize properties that need to configure enableVisualizedProperties

// 开启可视化全埋点自定义属性配置下发 saConfigOptions.enableVisualizedProperties(true);
JAVA

If this property is false, the created visual custom property cannot be collected. Turn on this switch to turn on the visual buried point by default.

  • Before using this feature, make sure you have completed it in your Android projectConfigure Scheme
  • For the use of visual full burial points in the analysis of divine plans, please refer to the visual full tracking section

8.5. Enable the click analysis function

Version requirements

  • Sensors Analytics v2.2.0.240
  • Android SDK v5.0.0 version and above
  • This feature relies on the activation of event capture by clicking on all buried points
  • Before using this function, ensure that the Scheme of the current project is configured in your App. For details, seeConfigure Scheme

Before SDK initialization callSAConfigOptions instance enableHeatMap() method, and pass the parameter true to enable the SDK's click analysis function:

saConfigOptions.enableHeatMap(true);
CODE

After the App click analysis is enabled, the function takes effect on all clicks on the page by default. If you only want to perform heat map on some pages, you can useaddHeatMapActivity() or addHeatMapActivities() method to configure:

//开启某个 Activity 的点击图 SensorsDataAPI.sharedInstance().addHeatMapActivity(Class<?> activity); //开启多个 Activity 的点击图 SensorsDataAPI.sharedInstance().addHeatMapActivities(List<Class<?>> activitiesList);
CODE

8.6. The debugging mode dynamic configuration function is enabled

In Sensors Android SDK (3.0.3+), you can enable the "debug mode" of the device by scanning the two-dimensional code on the web page. For details about the debugging mode configuration, seeDebugging mode Dynamic configuration.

8.7. Enable the automatic collection of Crash information

By default, the SDK disables Crash information collection. After the collection is enabled, an App Crash is triggeredAppCrashed event, the stack information is recorded in app_crashed_reason properties.

SAConfigOptions saConfigOptions = new SAConfigOptions(SA_SERVER_URL); //利用初始化的 SAConfigOptions 对象开启 crash 信息采集 saConfigOptions.enableTrackAppCrash(); SensorsDataAPI.startWithConfigOptions(this, saConfigOptions);
CODE

v3.1.0 and earlier versions, enable Crash Collection:

//开启 crash 信息收集 SensorsDataAPI.sharedInstance().trackAppCrash();
CODE

8.8. SDK Network Request Switch

The SDK provides the interface enableNetworkRequest(boolean isRequest) to control the SDK's network request. The parameter true means allowing the SDK to initiate network requests, and false means prohibiting the SDK from initiating network requests. Please pay attention to the timing of the call to prevent the SDK from being in a disabled network state, causing events to not be reported in a timely manner.

// 开启网络请求 SensorsDataAPI.sharedInstance().enableNetworkRequest(true); // 禁用网络请求 SensorsDataAPI.sharedInstance().enableNetworkRequest(false);
CODE

8.9. Real-time Event Collection

The SDK provides the interface setInstantEvents(List&lt;String&gt; listInstantEvents) during initialization to set instant events for real-time marketing scenarios.

List list = new ArrayList(); list.add("instant_event1"); list.add("instant_event2"); SAConfigOptions configOptions = new SAConfigOptions(SA_SERVER_URL); //设置实时上报数据事件名称列表 configOptions.setInstantEvents(list);
CODE

This interface is applicable only to real-time marketing scenarios and has no actual meaning for other businesses.