Access to the On Device Sentiance Insights is available through the APIs exposed by the Sentiance SDK (iOS, Android, React Native and Flutter) .
Available Insights
The On Device API provides access to following insights:
Driving Insights
Mobility Insights
Lifestyle Insights
Fetching Insights
Depending on your use-case and the technical design of your application, you have two options to retrieve insights:
Querying the SDK on Demand
Listening to Callbacks for Real-time Updates
Querying the SDK on Demand
You can query the SDK for insights at any point in your application codebase. The following example demonstrates how to fetch the recent events:
let currentDate = Date()
let calendar = Calendar.current
let fiveDaysAgo = calendar.date(byAdding: .day, value: -5, to: currentDate)
let events = Sentiance.shared.getTimelineEvents(from: fiveDaysAgo!, to: currentDate)
events.forEach { event in
print(event.eventId)
}
val from = Date(0)
val to = Date(Long.MAX_VALUE)
EventTimelineApi.getInstance(context).getTimelineEvents(from, to).forEach { event ->
print("Event ID: ${event.id}")
}
import EventTimelineApi from '@sentiance-react-native/event-timeline';
const from = new Date(0); // 01/01/1970
const to = new Date(2 ** 31 * 1000);
const events = await EventTimelineApi.getTimelineEvents(from.getTime(), to.getTime());
for (const event of events) {
console.log(`Event ID: ${event.id}`);
}
import 'package:sentiance_event_timeline/sentiance_event_timeline.dart';
final sentianceEventTimeline = SentianceEventTimeline();
const int maxLongValue = 9223372036854775807;
final events = await sentianceEventTimeline.getTimelineEvents(0, maxLongValue);
for (var event in events) {
print("Event ID: ${event.id}");
}
Similarly, you can request various insights. Read through the full example and explore SDK API Reference for a comprehensive list of available APIs
Listening to Callbacks for Real-time Updates
When setting up callbacks for real-time updates, it's crucial to ensure that you attach the listener at the appropriate location in your code.
The listeners should be included in the app boot-up scripts, right after executing the SDK initialization commands.
Below is an example of how to listen to TimelineEvent updates in real-time:
// MainApplication.kt
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
initializeSentianceSdk()
}
private fun initializeSentianceSdk() {
val sentiance = Sentiance.getInstance(this)
val initOptions = SentianceOptions.Builder(this)
.setNotification(NotificationHelper.createNotification(this), NOTIFICATION_ID)
.build()
sentiance.initialize(initOptions)
listenForUpdates()
}
fun listenForUpdates() {
val api = EventTimelineApi.getInstance(this)
api.setTimelineUpdateListener { event ->
Log.v(TAG, event.eventId) // <-------
}
}
}
listenForUpdates(); // Start listening to event updates
async function listenForUpdates() {
await EventTimelineApi.addTimelineUpdateListener((event) => {
console.log(event.eventId) // <---------
});
}
In order to listen to timeline event updates in real time, you need to make changes to your Dart code in addition to your native code (depending on which platform you're dealing with)
Dart setup
Create a background.dart file with the following code:
background.dart
import 'package:sentiance_event_timeline/sentiance_event_timeline.dart';
// The annotation indicates that this method should be preserved during
// tree-shaking and is considered a Dart entry point.
@pragma('vm:entry-point')
void registerEventTimelineListener() {
// Ensures that the Flutter framework is properly initialized
WidgetsFlutterBinding.ensureInitialized();
// Set an event timeline listener
SentianceEventTimeline.registerEventTimelineUpdateListener((event) {
print("Received timeline event ${event.toString()}");
if (event is TransportEvent) {
print("Received transport event: ${event.toString()}");
} else if (event is StationaryEvent) {
print("Received stationary event: ${event.toString()}");
} else if (event is OffTheGridEvent) {
print("Received off the grid event: ${event.toString()}");
} else if (event is UnknownEvent) {
print("Received unknown event: ${event.toString()}");
}
}
}
Android setup
Inside your Application class, add the following code inside the onCreate method to set up a native event timeline listener and have it invoke your Dart code with event timeline updates:
import android.app.Application
import com.sentiance.core_plugin.CorePlugin
import com.sentiance.event_timeline_plugin.EventTimelinePlugin
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
// Initialize the SDK
CorePlugin.initialize(this)
// This is the name of your Flutter app's package,
// which is specified on your pubspec.yaml file
val flutterAppPackageName = "my_flutter_app"
// The name of the dart file where your Dart entry point resides
val dartFileName = "background.dart"
// the name of the Dart function that will be responsible of handling
// event timeline updates
val dartEntryPoint = "registerEventTimelineListener"
val dartLibrary = "package:$flutterAppPackageName/$dartFileName"
// Set up a native listener
EventTimelinePlugin.initializeListener(this, dartLibrary, dartEntryPoint)
}
}
iOS setup
Inside your AppDelegate class, add the following code to set up a native event timeline listener and have it invoke your Dart code with event timeline updates:
A common practice when utilizing On-Device Insights involves ensuring the insights are effectively synchronised with your backend storage systems. This step is essential for integrating real-time data insights directly into your data management workflows.
Deciding on the optimal placement of listeners is crucial for syncing data with your backend, based on whether the application is in the foreground or background. This ensures that the insights remain accessible to the underlying systems at all times.
For background syncing, place listeners in startup scripts to activate when the app is woken by the OS. For foreground syncing, integrate listeners either in startup scripts or in specific startup functions as the user begins their session, ensuring seamless data sync with your backend in all app states.
Insert the listeners within AppDelegate.swift file just following the Sentiance.shared.initialize initiation step. This placement ensures they are primed to manage background processes as soon as the application initiates.
Insert the listeners within MainApplication.kt class just following the Sentiance.getInstance(this).initialise() initiation step. This placement ensures they are primed to manage background processes as soon as the application initiates.
The Sentiance SDK automatically activates the index.js file when the app is woken up, eliminating the need for background syncing setup in the native code. You can simply add your listeners to the index.js file to handle background activities efficiently.
// index.js
import { AppRegistry } from 'react-native'
import App from './src/App'
import { name as appName } from './app.json'
export const attachListeners = () => {
// attach listeners here
}
AppRegistry.registerComponent(appName, () => App)
attachListeners()
To handle background detections efficiently, make sure to setup/register your listeners appropriately in your Dart + native code as outlined in the previous section.