LogoLogo
SentianceInsights-Control-TowerLegacy DocsImportant Security Notice
  • Introduction
  • Integrating the SDK
    • Getting Started
    • Android Quick Start
      • 1. Including the SDK
      • 2. Initialization
      • 3. User Creation
      • 4. Enabling Detections
      • 5. SDK Status Updates
      • 6. Permissions
      • 7. Additional Requirements
    • iOS Quick Start
      • 1. Including the SDK
        • Using CocoaPods
        • Using Carthage
        • Using Swift Package Manager
        • Manual Integration
      • 2. Project Settings
      • 3. Initialization
      • 4. User Creation
      • 5. Enabling Detections
      • 6. SDK Status Updates
      • 7. Permissions
      • 8. Additional Requirements
    • React Native Quick Start
      • 1. Including the SDK
      • 2. Configuration
      • 3. Initialization
      • 4. User Creation
      • 5. Enabling Detections
      • 6. SDK Status Updates
    • Flutter Quick Start
      • 1. Including the SDK
      • 2. Configuration
      • 3. Initialization
      • 4. User Creation
      • 5. Enabling Detections
      • 6. SDK Status Updates
    • What Comes After Integration
    • Integration (FAQ)
    • Detections (FAQ)
  • Sentiance Insights
    • Overview of Sentiance Insights
      • Driving Insights
        • Transports
        • Driving Events and Scores
        • Car Crashes
      • Mobility and Lifestyle Insights
        • Visit Essentials
        • User Segmentation
    • Engagement
      • User Adaptive Score
      • Streaks
      • Challenges
      • Reward System
      • Communication Campaign
      • Social Groups
        • Technical Details
    • Accessing Sentiance Insights
      • via On Device API
      • via Cloud API
      • via Firehose - Realtime Messages
      • via Offloads
  • FAQ
    • Security, Privacy and Terms of Service (FAQ)
  • Important topics
    • SDK
      • Appendix
        • Android
          • Android 10 Update Behavior
          • Android Battery Optimization
          • Artifacts & Dependencies
          • Manifest Permissions
          • Notification Management
          • Sample Notification
          • Supported API Levels
        • iOS
          • App Store Privacy Section
          • App Store Release
          • Apple Privacy Manifest
          • ARM Simulator Support
          • Dependencies
          • iOS 13 permission changes
          • Supported iOS Versions & Architectures
          • Swift Support
          • v5.x Framework Files
          • v6.x Framework Files
        • Controlled Detections
          • Automatic Detections
          • Automatic Detections with Forced Trips
          • Controlled Trips Only
          • Checking Trip Status
        • Control Sending Data
        • Custom User Metadata
        • Detecting Vehicle Crashes
        • Feature Production Readiness
        • Migration Guide
          • Android
          • iOS
          • React Native
          • Flutter
        • On-Device Features
        • React Native
        • SDK Initialization
        • User Access Token
        • User Creation
        • User Linking
        • Xamarin
      • API Reference
        • Android
          • AsyncInitializationError
          • AsyncInitializationResult
          • DateTime
          • DetectionStatus
          • DisableDetectionsError
          • DisableDetectionsResult
          • Driving Insights
            • CallWhileMovingEvent
            • DrivingInsight
            • DrivingInsightsApi
            • DrivingInsightsReadyListener
            • HarshDrivingEvent
              • Type
            • PhoneUsageEvent
            • SafetyScores
            • SafetyScoreRequestParameters
              • Builder
              • OccupantRoles
              • Period
              • TransportModes
            • SpeedingEvent
          • Smart Geofences
            • DetectionMode
            • SmartGeofence
            • SmartGeofenceApi
            • SmartGeofenceEvent
              • Type
            • SmartGeofenceEventListener
            • SmartGeofencesRefreshError
              • SmartGeofencesRefreshFailureReason
            • SmartGeofencesRefreshResult
          • EnableDetectionsError
            • EnableDetectionsFailureReason
          • EnableDetectionsResult
          • EventTimeline
            • EventType
            • TransportMode
            • Event
              • OffTheGridEvent
              • StationaryEvent
              • TransportEvent
              • UnknownEvent
            • EventTimelineUpdateListener
            • EventTimelineApi
            • OccupantRole
            • Venue
              • VenueType
              • VenueSignificance
          • Feedback
            • FeedbackApi
            • OccupantRoleFeedback
            • OccupantRoleFeedbackResult
          • GeoLocation
          • InitializationResult
            • InitializationFailureReason
          • InitState
          • MetaUserLinker
          • MetaUserLinkerAsync
          • MetaUserLinkerCallback
          • OnInitCallback
            • InitIssue
          • OnSdkStatusUpdateHandler
          • OnStartFinishedHandler
          • PendingOperation
            • OnSuccessListener
            • OnFailureListener
            • OnFailureListener
            • OnCompleteListener
          • ResetCallback
            • ResetCallback.ResetFailureReason
          • ResetError
            • ResetFailureReason
          • ResetResult
          • SdkConfig
            • LocationPermission
            • Builder
          • SdkException
          • SdkStatus
            • LocationSetting
            • Quota Status
            • StartStatus
          • SdkStatusUpdateListener
          • Sentiance
          • SentianceOptions
            • SentianceOptions.Builder
          • StartTripError
            • StartTripFailureReason
          • StartTripResult
          • StationaryInfo
          • StopTripError
            • StopTripFailureReason
          • StopTripResult
          • SubmitDetectionsCallback
          • SubmitDetectionsError
            • SubmitDetectionsFailureReason
          • SubmitDetectionsResult
          • Token
          • TokenResultCallback
          • TransmittableDataType
          • Transport Sessions
            • SensorDataChunk
            • TransportSession
            • TransportSessionApi
            • TransportSessionListener
          • Trip
            • StartTripCallback
            • StopTripCallback
            • TransportMode
            • TripTimeoutListener
            • TripType
          • TripInfo
          • UserAccessTokenError
            • UserAccessTokenFailureReason
          • UserActivity
          • UserActivityListener
          • UserActivityType
          • UserContext
            • Attribute
            • Segment
              • SegmentCategory
              • SegmentSubcategory
              • SegmentType
            • SemanticTime
          • UserContextApi
            • RequestUserContextFailureReason
            • RequestUserContextError
            • UserContextUpdateCriteria
            • UserContextUpdateListener
          • UserCreationError
            • UserCreationFailureReason
          • UserCreationOptions
            • UserCreationOptions.Builder
          • UserCreationResult
            • UserInfo
          • UserLinker
          • UserLinkerAsync
          • UserLinkerCallback
          • UserLinkingError
            • UserLinkingFailureReason
          • UserLinkingResult
          • VehicleCrashDetection
            • CrashDetectionApi
            • CrashDetectionState
            • VehicleCrashDiagnostic
            • VehicleCrashEvent
            • VehicleCrashDiagnosticListener
            • VehicleCrashListener
            • VehicleCrashSeverity
          • Waypoint
        • iOS
          • Detections
            • Enable Detections
            • Disable Detections
          • Driving Insights
            • SENTCallWhileMovingEvent
            • SENTDrivingInsights
            • SENTDrivingInsightsReadyDelegate
            • SENTHarshDrivingEvent
              • HarshDrivingEventType
            • SENTPhoneUsageEvent
            • SENTSpeedingEvent
            • SENTSafetyScores
            • SafetyScoreRequestParameters
              • SafetyScoreRequestOccupantRoleOption
              • SafetyScoreRequestPeriod
              • SafetyScoreRequestTransportModeOption
          • Event Timeline
            • EventTimelineDelegate
            • SENTOccupantRole
            • SENTTimelineEvent
              • SENTOffTheGridEvent
              • SENTStationaryEvent
              • SENTTransportEvent
              • SENTUnknownEvent
            • SENTTimelineEventType
            • SENTTimelineTransportMode
            • SENTVenue
            • SENTVenueSignificance
            • SENTVenueType
          • Feedback
            • SENTFeedback
            • SENTOccupantRoleFeedback
            • SENTOccupantRoleFeedbackResult
          • SENTCompletionHandlers
          • SENTConfig
          • SENTDate
          • SENTGeolocation
          • SENTAsyncInitializationCompletionHandler
          • SENTAsyncInitializationError
          • SENTAsyncInitializationResult
          • Sentiance
          • SENTInitializationResult
          • SENTOptions
            • SENTOptionsInitPurpose
          • SENTPublicDefinitions
          • SENTSDKStatus
          • SENTToken
          • SENTTransmittableDataType
          • SENTUserActivity
          • SENTVehicleCrashDetectionState
          • SENTVehicleCrashDiagnostic
          • SENTVehicleCrashEvent
            • SENTVehicleCrashSeverity
          • SENTWaypoint
          • Smart Geofences
            • SENTSmartGeofencesRefreshHandler
            • SmartGeofenceDetectionMode
            • SmartGeofencesRefreshError
              • SmartGeofencesRefreshFailureReason
            • SmartGeofencesRefreshResult
            • SmartGeofence
            • SmartGeofenceEvent
              • SmartGeofenceEventType
            • SmartGeofenceEventDelegate
          • Transport Sessions
            • SENTAccelerometerDataIterator
            • SENTLocationDataIterator
            • SENTSensorDataChunk
            • SENTTransportSession
          • User Context
            • SENTAttribute
            • SENTRequestUserContextCompletionHandler
            • SENTRequestUserContextError
            • SENTRequestUserContextFailureReason
            • SENTSegment
              • SENTSegmentCategory
              • SENTSegmentSubCategory
              • SENTSegmentType
            • SENTSemanticTime
            • SENTUserContext
            • SENTUserContextDelegate
            • SENTUserContextUpdateCriteria
          • User Creation & Linking
            • SENTUserInfo
            • User Creation
              • SENTUserCreationResult
              • SENTUserCreationFailureReason
              • SENTUserCreationError
              • SENTUserCreationCompletionHandler
              • SENTUserCreationOptions
            • User Linking
              • SENTNoOpUserLinker
              • SENTUserLinkingResult
              • SENTUserLinkingFailureReason
              • SENTUserLinkingError
              • SENTUserLinkingCompletionHandler
              • SENTUserLinker
        • React Native
          • core
            • Definitions
            • Examples
          • crash-detection
            • Definitions
            • Examples
          • driving-insights
            • Definitions
            • Examples
          • smart-geofences
            • Definitions
            • Examples
          • event-timeline
            • Definitions
            • Examples
          • legacy
            • Definitions
            • Examples
          • user-context
            • Definitions
            • Examples
        • Flutter
      • Battery Optimization on Android
      • How To
        • Check the Location Permissions
        • Utilize the Event Timeline API
        • Utilize the Driving Insights API
        • Utilize the User Context API
        • Utilize the Smart Geofences API
      • Troubleshooting
        • Android
        • iOS
      • Changelog
        • Android
        • iOS
        • React Native
        • Flutter
    • Authentication and Authorization
    • User Creation (via Authentication Code)
    • User Deletion
    • PlayStore Location Access Review
    • Privacy Report & Dashboard
    • Crash Detection
    • Important Security Notice
    • Injecting Fake Data
    • Custom Aggregation For Analytics
    • Merging Scores for Motorcycles and Cars
  • Links
    • SDK Standard License
    • Insights-by-Sentiance Application
    • Insights-by-Sentiance Privacy Policy
    • Journeys License
    • Technical & Organizational Measures
Powered by GitBook
On this page
  • Available Insights
  • Fetching Insights
  • Querying the SDK on Demand
  • Listening to Callbacks for Real-time Updates
  • Synchronising Insights with Your Backend
  1. Sentiance Insights
  2. Accessing Sentiance Insights

via On Device API

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:

  1. Querying the SDK on Demand

  2. 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}");
}

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:

//  AppDelegate.swift

import SENTSDK
import UIKit

@main

class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {        
        initializeSentianceSDK(launchOptions: launchOptions)
        return true
    }
    
    private func initializeSentianceSDK(launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
        let options = SENTOptions(for: .appLaunch)
        let initializationResult = Sentiance.shared.initialize(options: options, launchOptions: launchOptions)     
        Sentiance.shared.eventTimelineDelegate = EventTimelineUpdateReceiver.shared // <-------
    }

    ...
    ...
}

// EventTimelineUpdateReceiver.swift
class EventTimelineUpdateReceiver : EventTimelineDelegate {
    static let shared = EventTimelineUpdateReceiver()
    func onEventTimelineUpdate(event: SENTTimelineEvent) {
        print(event.eventId)
    }
}
// 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:

import Flutter
import UIKit
import sentiance_core
import sentiance_event_timeline

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        // Register plugins
        GeneratedPluginRegistrant.register(with: self)
        
        // Initialize the SDK
        SentianceCorePlugin.shared.initialize()
        
        // Set up a native listener
        SentianceEventTimelinePlugin.initializeListener(
            withEntryPoint: "registerEventTimelineListener",
            libraryURI: "package:my_flutter_app/background.dart"
        )
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}

Synchronising Insights with Your Backend

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.

Additional helpful links:

PreviousAccessing Sentiance InsightsNextvia Cloud API

Last updated 6 months ago

Similarly, you can request various insights. Read through the and explore for a comprehensive list of available APIs

full example
SDK API Reference
SDK API Reference
More On-Device How-to Guides
On Device features