Search…
React Native
1
import RNSentiance from "react-native-sentiance";
Copied!
In order for the SDK to start collecting data you would need to perform two steps.
  1. 1.
    Create a SDK User
  2. 2.
    Start the SDK

Create User and start the Sentiance SDK

Create a user and start the sentiance SDK. The following should be placed where and when your application is ready to start collecting data (e.g. on user login, on reaching a particular page)

Without User Linking

1
await RNSentiance.createUserExperimental({
2
credentials: { appId, appSecret, baseUrl },
3
});
4
await RNSentiance.start();
Copied!

With User Linking

Please refer to https://docs.sentiance.com/guide/user-linking for documentation on the user linking.
1
await RNSentiance.createUserExperimental({
2
credentials: { appId, appSecret, baseUrl },
3
linker: async (data, done) => {
4
// request your backend to perform user linking
5
await linkUser(data.installId);
6
7
// Ensure you call the "done" after
8
done();
9
},
10
});
11
await RNSentiance.start();
Copied!
If your backend was unable to link the user to the Sentiance platform, execute done(false) instead to notify the SDK that the linking failed

Stopping the Sentiance SDK

Stopping is only allowed after successful initialization. While it's possible to "pause" the detections modules of the Sentiance SDK's, it's not recommended.
1
try {
2
const stopResponse = await RNSentiance.stop();
3
// SDK stopped properly.
4
} catch (err) {
5
// An error prevented the SDK from stopping correctly
6
}
Copied!

Init status

Checking if SDK is initialized
1
const initState = await RNSentiance.getInitState();
2
const isInitialized = initState == "INITIALIZED";
Copied!

SDK status

The status of the Sentiance SDK
1
const sdkStatus = await RNSentiance.getSdkStatus();
Copied!
The SDK can signal SDK status updates to JavaScript without being invoked directly. You can subscribe to these status updates by creating a new NativeEventEmitter instance around your module, and adding a listener for SDKStatusUpdate.
1
import { NativeEventEmitter } from "react-native";
2
3
const sentianceEmitter = new NativeEventEmitter(RNSentiance);
4
const subscription = sentianceEmitter.addListener("SDKStatusUpdate", (res) => {
5
// Returns SDK status
6
});
7
8
// Don't forget to unsubscribe, typically in componentWillUnmount
9
subscription.remove();
Copied!

Get SDK version

1
const version = await RNSentiance.getVersion();
Copied!

Get user id

If the SDK is initialized, you can get the user id as follows. This user id will allow you to interact with the API's from Sentiance. You need a token and user to authorize requests and query the right data.
1
const userId = await RNSentiance.getUserId();
Copied!

Get user access token

If the SDK is initialized, you can get a user access token as follows. This token will allow you to interact with the API's from Sentiance. You need a token and user to authorize requests and query the right data. If the token has expired, or will expire soon, the SDK will get a new bearer token before passing it to the callback. Generally, this operation will complete instantly by returning a cached bearer token, but if a new token has to be obtained from the Sentiance API, there is a possibility it will fail.
1
const { tokenId } = await RNSentiance.getUserAccessToken();
Copied!

Adding custom metadata

Custom metadata allows you to store text-based key-value user properties into the Sentiance platform. Examples are custom user id's, application related properties you need after the processing, ...
1
const label = "correlation_id";
2
const value = "3a5276ec-b2b2-4636-b893-eb9a9f014938";
3
4
await RNSentiance.addUserMetadataField(label, value);
Copied!

Remove custom metadata

You can remove previously added metadata fields by passing the metadata label to the removeUserMetadataField function.
1
const label = "correlation_id";
2
3
await RNSentiance.removeUserMetadataField(label);
Copied!

Adding multiple custom metadata fields

You can add multiple custom metadata fields by passing an object to the addUserMetadataFields function.
1
const metadata = { corrolation_id: "3a5276ec-b2b2-4636-b893-eb9a9f014938" };
2
3
await RNSentiance.addUserMetadataFields(metadata);
Copied!

Starting trip

Whenever you call startTrip on the SDK, you override moving state detection and the SDK will track the trip until you call stopTrip or until the timeout (2 hours) is reached. startTrip accepts a metadata object and a transport mode hint (number) as parameters.
Transport mode hint:
1
SENTTransportModeUnknown = 1,
2
SENTTransportModeCar = 2,
3
SENTTransportModeBicycle = 3,
4
SENTTransportModeOnFoot = 4,
5
SENTTransportModeTrain = 5,
6
SENTTransportModeTram = 6,
7
SENTTransportModeBus = 7,
8
SENTTransportModePlane = 8,
9
SENTTransportModeBoat = 9,
10
SENTTransportModeMetro = 10,
11
SENTTransportModeRunning = 11
Copied!
Example:
1
const metadata = { corrolation_id: "3a5276ec-b2b2-4636-b893-eb9a9f014938" };
2
const transportModeHint = 1;
3
4
try {
5
await RNSentiance.startTrip(metadata, transportModeHint);
6
// Trip is started
7
} catch (err) {
8
// Unable to start trip
9
}
Copied!

Stopping trip

1
try {
2
const trip = await RNSentiance.stopTrip();
3
// Stopped trip
4
} catch (err) {
5
// Unable to stop trip
6
}
Copied!
The SDK can also signal trip timeouts to JavaScript. You can subscribe to these trip timeouts by creating a new NativeEventEmitter instance around your module, and adding a listener for TripTimeout.
1
import { NativeEventEmitter } from "react-native";
2
3
const sentianceEmitter = new NativeEventEmitter(RNSentianceLibrary);
4
const subscription = sentianceEmitter.addListener("TripTimeout", () => {
5
// Trip timeout received
6
});
Copied!

Trip status

Checking trip status
1
const isTripOngoing = await RNSentiance.isTripOngoing();
Copied!

Control sending data

If you want to override the default behavior, you can initiate a force submission of detections. Ideally, you use this method only after explaining to the user that your app will consume more bandwidth in case the device is not connected to Wi-Fi.
1
try {
2
await RNSentiance.submitDetections();
3
} catch (err) {
4
// Something went wrong with submitting data, for more information, see the error variable
5
}
Copied!

Disk, mobile network and Wi-Fi quotas

The actual usages and limits in bytes can be obtained using the getWiFiQuotaUsage, getWiFiQuotaLimit and similar methods on the Sentiance SDK interface.
1
const limit = await RNSentiance.getWiFiQuotaLimit();
Copied!
All quota functions:
  • getWiFiQuotaLimit
  • getWiFiQuotaUsage
  • getMobileQuotaLimit
  • getMobileQuotaUsage
  • getDiskQuotaLimit
  • getDiskQuotaUsage

User Activity

Get user current activity
1
const userActivity = await RNSentiance.getUserActivity();
Copied!
The SDK can signal user activity updates to JavaScript without being invoked directly. You can subscribe to these user activity updates by creating a new NativeEventEmitter instance around your module, and adding a listener for SDKUserActivityUpdate.
1
import { NativeEventEmitter } from "react-native";
2
3
const sentianceEmitter = new NativeEventEmitter(RNSentiance);
4
const subscription = sentianceEmitter.addListener(
5
"SDKUserActivityUpdate",
6
(userActivity) => {
7
// Handle user activity
8
}
9
);
10
11
RNSentiance.listenUserActivityUpdates();
12
13
// Don't forget to unsubscribe, typically in componentWillUnmount
14
subscription.remove();
Copied!
Handling user activity
1
const { type, tripInfo, stationaryInfo } = userActivity;
2
3
if (type === "USER_ACTIVITY_TYPE_STATIONARY") {
4
const { location } = stationaryInfo;
5
6
if (location) {
7
const { latitude, longitude } = location;
8
}
9
//..
10
} else if (type === "USER_ACTIVITY_TYPE_TRIP") {
11
//..
12
} else if (type === "USER_ACTIVITY_TYPE_UNKNOWN") {
13
//..
14
}
Copied!

Update SDK foreground notification (ANDROID ONLY)

Updates the title and text of SDK notification. After calling this method, any notification shown by the SDK will be updated.
Note that this change is valid only during the process's lifetime. After the app process restarts, the SDK will display the default notification.
1
/** {string} title {string} message */
2
await RNSentiance.updateSdkNotification("RN SDK Sample", "SDK is running");
Copied!

Clearing/Resetting the SDK

To delete the Sentiance user and its data from the device, you can reset the SDK by calling RNSentiance.clear. This allows you to create a new Sentiance user by reinitializing the SDK, and link it to a new third party ID.
1
try {
2
await RNSentiance.clear();
3
// The SDK was successfully cleared and reset
4
} catch (err) {
5
// Resetting the SDK failed
6
// err.name has three values: SDK_INIT_IN_PROGRESS, SDK_RESET_IN_PROGRESS, SDK_RESET_UNKNOWN_ERROR
7
}
Copied!

Crash Event Detection(deprecated)

Subscribe to vehicle crash events.
1
import { NativeEventEmitter } from "react-native";
2
3
const sentianceEmitter = new NativeEventEmitter(RNSentiance);
4
const sdkCrashEventSubscription = sentianceEmitter.addListener(
5
"SDKCrashEvent",
6
({ time, lastKnownLocation }) => {
7
// parameter time is in milliseconds
8
// parameter lastKnownLocation is nullable
9
if (lastKnownLocation) {
10
const { latitude, longitude } = lastKnownLocation;
11
}
12
}
13
);
14
15
RNSentiance.listenCrashEvents();
16
17
// To unsubscribe
18
sdkCrashEventSubscription.remove();
Copied!

Trip Profiling

Handle on-device trip profiling

1
import { NativeEventEmitter } from "react-native";
2
3
const sentianceEmitter = new NativeEventEmitter(RNSentiance);
4
5
const sdkTripProfilesSubscription = sentianceEmitter.addListener(
6
"SDKTripProfile",
7
/**
8
* TripProfile: { tripId: String transportSegments: Array[ TransportSegment{
9
* startTime: number // milliseconds since 1970-01-01 endTime: number //
10
* milliseconds since 1970-01-01 vehicleMode: string, VEHICLE | NOT_VEHICLE |
11
* IDLE | UNKNOWN distance?: number // in meters averageSpeed?: number // the
12
* average speed travelled in m/s topSpeed?: number // the top speed travelled
13
* in m/s percentOfTimeSpeeding?: number // the percent of time the user was
14
* speeding hardEvents?: Array[ HardEvent{ magnitude: number, the magnitude of
15
* this hard event in m/s2 timestamp: milliseconds since 1970-01-01 } ] } ] }
16
*/
17
(tripProfile) => {}
18
);
19
RNSentiance.listenTripProfiles();
20
21
// To unsubscribe
22
sdkTripProfilesSubscription.remove();
Copied!

Update Trip profiling config

1
/**
2
* EnableFullProfiling: If set to true, full trip profiling will be enabled
3
* allowing the Sentiance platform to profile the trip and the results made
4
* available via the API. In addition, the app will no longer receive trip
5
* profiles via the "SDKTripProfile" listener. If set to false, on-device trip
6
* profiling will be enabled. speedLimit: Sets the speed limit in km/h, which is
7
* used to determine the percent of time the user was speeding. If null, the SDK
8
* will use an internal default value.
9
*/
10
try {
11
await RNSentiance.updateTripProfileConfig({
12
enableFullProfiling: false,
13
speedLimit: 80,
14
});
15
} catch (err) {
16
console.error(err);
17
}
Copied!
Determine if the app should initialize Sentiance SDK natively
To make user linking possible, the first SDK initialization should be executed in JS. After it completes successfully, await RNSentiance.enableNativeInitialization() should be invoked.
In AppDelegate (iOS) and MainApplication (Android), isNativeInitializationEnabled can be used to determine if the SDK should be initialized natively.
To disable native initialization, invoke await RNSentiance.disableNativeInitialization().
Please refer to our example app for a complete usage.

Invoke a dummy vehicle crash event

1
await RNSentiance.invokeDummyVehicleCrash();
Copied!

Check if crash detection is supported

1
const crashDetectionSupported =
2
await RNSentiance.isVehicleCrashDetectionSupported("TRIP_TYPE_SDK");
3
if (crashDetectionSupported) {
4
// setup vehicle crash event listener
5
}
Copied!

Vehicle Crash Event Detection

Listen to vehicle crash events.
1
import { NativeEventEmitter } from "react-native";
2
3
const sentianceEmitter = new NativeEventEmitter(RNSentiance);
4
const vehicleCrashEventSubscription = sentianceEmitter.addListener(
5
"VehicleCrashEvent",
6
(event: VehicleCrashEvent) => {}
7
);
8
9
RNSentiance.listenVehicleCrashEvents();
10
11
// To unsubscribe
12
vehicleCrashEventSubscription.remove();
Copied!