Basic API Introduction (React Native)
|
Collect
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. Records the user properties that were set for the first time
We can use properties that are only valid when first setprofileSetOnce() record these attributes. Different fromprofileSet() 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() This parameter is applicable to setting the first activation time and first registration time. For example:
// 设定用户渠道为 "developer@sensorsdata.cn" 的 "AdSource" 属性值为 "XXX Store" sensors.profileSetOnce({ AdSource: "XXX Store" }) // 再次设定用户渠道,设定无效, "AdSource" 属性值仍然是 "XXX Store" sensors.profileSetOnce({ AdSource : "Email" })
2.2. Attributes of a numeric type
For numeric user properties, you can use profileIncrement() add the property values. It is often used to record attributes such as the number of user payments, payment amount, and points. For example:
// 将用户游戏次数属性增加一次 sensors.profileIncrement("GamePlayed", 1);
2.3. 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:
// 设定用户观影列表属性,设定后属性 "Movies" 为: ["Sicario", "Love Letter"] sensors.profileAppend('Movies', ['Sicario','Love Letter']);
Note that the element in the column phenotype attribute must be String type. For column phenotypic restrictions, seedata format.
2.4. Attribute cancellation
If you need to cancel a user property that has been set, you can call profileUnset() to cancel:
sensors.profileUnset("age");
3. Tracking event acquisition
After SDK initialization is complete, you can bury data through the following interface.
3.1. Code bury trace event
After initialize SDK, you can usetrack() method track user behavior events and adds custom properties to events.
//触发一条 BuyProduct 事件,同时设置商品 ID、商品类别属性 sensors.track('BuyProduct', { ProductID: 123456, ProductCatalog:'Laptop Computer'})
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 eventtrackTimerStart("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:
sensors.trackTimerStart('ViewProduct'); // 调用 track,记录 ViewProduct 事件,并在属性 event_duration 中记录用户浏览商品的时间 sensors.trackTimerEnd('ViewProduct', {product_id:'PRODUCT_ID'});
Multiple call trackTimerStart("Event") , the start time of event "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.
Statistical event duration supports pause and recovery by calling trackTimerPause(String eventName) and trackTimerResume(String eventName) to pause and resume, respectively. Called if the recorded duration event needs to be cleared clearTrackTimer() interface.
3.3. Item metadata report
3.3.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 的物品,设置物品属性 sensors.itemSet('itemType', 'itemId', { price: 100, })
3.3.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 sensors.itemDelete(itemType, itemId);
4. event attributes
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
Can call getPresetProperties() method obtain 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.
//获取预置属性 sensors.getPresetPropertiesPromise().then((result) => { var presetProperties = result; })
4.2. Static public attribute
Static public properties are properties that need to be added for all events, and can be passed after initializing the SDK registerSuperProperties() register the property as a public property. The setting method is as follows:
// 将应用名称作为事件公共属性,后续所有 track 类型事件都会自动带上 "AppName" 属性 sensors.registerSuperProperties({ AppName: 'AppName' })
A registered static public property can be deleted by using the unregisterSuperProperty(key:string) method.
4.3. Set the dynamic public attribute of an event
All events in the application lifecycle need to be added, and the attribute value changes frequently. After initializing the SDK, it can be used registerDynamicSuperProperties() method to obtain the listener:
import sensors from 'sensorsdata-analytics-react-native'; var dynamic = sensors.registerDynamicSuperProperties(); //赋值给监听对象的 properties 属性,设置为动态公共属性 onPress={() => { dynamic.properties = {subject.key1:subject.key2} } }
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 acquisition
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:
- Whether WIFI/2G/3G/4G/5G network conditions
- Whether one of the sending conditions is met:
- Whether the time interval between the last sending is greater than flushInterval
- Whether the number of local cache logs is greater than flushBulkSize
- The type of event login() method triggers $SignUp event
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 call flush() method, force data to be sent to divine analytics, for example:
// 记录用户登录事件 sensors.track("UserLogin"); // 强制发送数据 sensors.flush();
The SDK is called when the App enters the background state or when the network switches to a network 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.sensors.setFlushNetworkPolicy() method to specify a network policy for sending data. For example:
/** * 设置 flush 时网络发送策略,默认 3G、4G、WI-FI 环境下都会尝试 flush * TYPE_NONE = 0;//NULL * TYPE_2G = 1;//2G * TYPE_3G = 1 << 1;//3G 2 * TYPE_4G = 1 << 2;//4G 4 * TYPE_WIFI = 1 << 3;//WIFI 8 * TYPE_5G = 1 << 4;//5G 16 * TYPE_ALL = 0xFF;//ALL 255 * 例:若需要开启 4G 5G 发送数据,则需要设置 4 + 16 = 20 */ //指定只在 3G/4G/WIFI 条件下发送数据。 sensors.setFlushNetworkPolicy(14);
5.3. Clear local cache events
Can use deleteAll() method, delete all events stored locally by the App.
Do not call this method unless specifically requested.
//删除 App 本地存储的所有事件 sensors.deleteAll();
6. 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, the Android SDK adds a 30-second session mechanism in order to cope with scenarios such as multi-process and forced killing. 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.
6.1. Open Full tracking
The SDK can automatically collect some user behaviors, such as App startup, exit, page browsing, and control clicks. When initializing the SDK, you can configure the type of full burial point that you want to enable:
sensors.init({ //... 其他配置 auto_track:SAAutoTrackType.START|SAAutoTrackType.END|SAAutoTrackType.CLICK|SAAutoTrackType.VIEW_SCREEN })
6.2. Ignore React Native embedded-point acquisition
Due to the presence of hybrid development scenarios, support for turning off React Native page browsing and element clicks separately, inproject package.json add sensorsData configuration:
{ "name": "reactNativeDemo", //... "sensorsData": { "ignoreScreen": true ,//忽略页面浏览 "ignoreClick": true //忽略点击事件 } }
You need to perform the configuration again node node_modules/sensorsdata-analytics-react-
native
/SensorsDataRNHook.js -run
command
6.3. 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.
6.3.1. Set the page customization properties
When jumping through Navigation, you can add custom properties to params. The SDK will automatically supplement or overwrite the properties of App page browsing events using the setting values in params.
<Button title="Go to PersonCenter" onPress={() => this.props.navigation.navigate('PersonCenter',{ sensorsdataparams:{ $title: 'title',//默认为 routename, param1: 'param1', param2: 'param2', }, }) }></Button>
6.3.2. Set the custom properties of the control
<Button onPress={() => {}} title="button" sensorsdataparams={{ name: 'button', ignore: true }} /> <TouchableHighlight onPress={() => {}} sensorsdataparams={{ name: 'TouchableHighlight', ignore: true }} > <Text style={{ fontSize: 20, padding: 10 }}>TouchableHighlight</Text> </TouchableHighlight>
6.4. Ignore a single page bury event
There are currently two ways to ignore $AppViewScreen events:
6.4.1. Mode 1
Adding the sensorsdataparams property to params ignores the page view event when it contains the SAIgnoreViewScreen property and the value is true, but the click event for the page is still $screen_name for the page.
createBottomTabNavigator( { Component: { screen: Tab1, params: { sensorsdataparams: { $screen_name: "screen", $title: "title", SAIgnoreViewScreen:true }, }, }, API: { screen: Tab2, }, Other: { screen: Tab3, }, } )
6.4.2. Mode 2
When navigating navigate through Navigate, pop, goBack, push, etc., add the sensorsdataparams property to params and ignore page browsing events when it contains the SAIgnoreViewScreen property and its value is true. But the click event for that page is still $screen_name for that page.
this.props.navigation.navigate(‘RouteName’, { sensorsdataparams: { $screen_name: "screen", $title: "title", SAIgnoreViewScreen : true }, })
6.5. Ignore component acquisition
Ignore the click event of the component when the ignore attribute in sensorsdataparams is set to true.
<Slider sensorsdataparams={{ name: 'Slider', ignore: true }} onSlidingComplete={() => {}} />
7. Full-track supported versions
- App element click event supports React Native 0.23 ~ 0.70.0;
- App page view event supports React Navigation ^2.0 ~ ^6.0;
- Visual full tracking requires React Native 0.46 ~ 0.70.0.
7.1. Manually trigger full tracking events
Manually triggering a full-track event means that the developer actively calls the interface provided by the SDK to trigger the app page view event. The difference between manually triggered events and automatically triggered full-track events by the SDK is that the value of lib_method for events triggered by developers is "code", while events triggered by the SDK are "autoTrack". It is recommended not to mix this feature with full-track to prevent event duplication.
7.1.1. Manually trigger page view event
The trackViewScreen() method can manually trigger the app page view event, and this interface is not limited by ignore conditions.
sensors.trackViewScreen(url, {title:'title'})
8. Other features
8.1. Visual full-track
8.1.1. Enable visual full-track
Version requirement
- Sensors Analytics v1.17.2517+
- Android SDK v4.0.0+
- iOS SDK
To enable visual full-track, configure the following during SDK initialization:
sensors.init({ //... 其他配置 visualized: { auto_track: true,// 可视化开关,默认 false } })
For Android initialization configuration, please refer to:
For iOS initialization configuration, please refer to:
8.1.2. Custom properties for visual full-track
Version Requirement
- Sensors Analytics v1.17.2517+
- Android SDK v6.0.0+
- iOS SDK
If you need to use custom properties for visualized auto tracking, you need to configure it as follows:
sensors.init({ //... 其他配置 visualized: { properties: true,// 可视化开关,默认 false } })
If this property is set to false, the created custom properties for visualized auto tracking cannot be collected. Turn on this switch to enable visualized auto tracking by default.
- Before using this feature, please make sure that you have completed the Scheme configuration in your Android project.
- For the use of visualized auto tracking in Sensors Analytics, please refer to visualized auto tracking.
Refer to the following example for Android initialization configuration:
Refer to the following example for iOS initialization configuration:
8.2. Enable click analysis functionality
Version Requirement
- Sensors Analytics v2.2.0.240
- Android SDK v5.0.0 or above
- This feature depends on the enablement of click event collection in auto tracking.
- Before using this feature, make sure to configure the Scheme of the current project in your app. For detailed operations, please refer to Scheme configuration.
The heat_map property was configured during SDK initialization
sensors.init({ //... 其他配置 heat_map: true })
8.3. SDK Network request switch
The SDK provides the enableNetworkRequest(boolean isRequest) interface to control network requests of the SDK. If true, the SDK is allowed to initiate network requests; if false, the SDK is forbidden to initiate network requests. When using the SDK, you must pay attention to the call time to prevent the SDK from being in the disabled network state, resulting in the failure to report events in time.
// 开启网络请求 sensors.enableNetworkRequest(true); // 禁用网络请求 sensors.enableNetworkRequest(false);
Note: The content of this document is a technical document that provides details on how to use the Sensors product and does not include sales terms; the specific content of enterprise procurement products and technical services shall be subject to the commercial procurement contract.