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
  • Query for Driving Insights
  • Subscribe for Driving Insights Updates
  • Query For Driving Events
  1. Important topics
  2. SDK
  3. How To

Utilize the Driving Insights API

PreviousUtilize the Event Timeline APINextUtilize the User Context API

Last updated 6 months ago

Accessing some of the API classes that are mentioned on this page requires additional Sentiance SDK dependencies. See for more information.

On this page, you can find examples of how to query the Sentiance SDK for driving insights, and how to register to receive real time driving insights in your app, for completed transports.

Query for Driving Insights

if let drivingInsights = Sentiance.shared.getDrivingInsights(forTransportId: transportId) {
    let event = drivingInsights.transportEvent
    let safetyScores = drivingInsights.safetyScores
    
    print("Focus score: \(safetyScores.focusScore ?? -1)")
    print("Legal score: \(safetyScores.legalScore ?? -1)")
    print("Smooth score: \(safetyScores.smoothScore ?? -1)")
    print("Call-while-moving score: \(safetyScores.callWhileMovingScore ?? -1)")
    print("Overall score: \(safetyScores.overallScore ?? -1)")

    print("Event ID: \(event.eventId)")
    print("Started on: \(event.startDate)")
    print("Ended on: \(String(describing: event.endDate))")
    print("Mode: \(event.transportMode)")

    if let distanceInMeters = event.distanceInMeters {
        print("Distance: \(distanceInMeters)")
    }

    print("Waypoints: \(event.waypoints)")
}
val drivingInsights = DrivingInsightsApi.getInstance(context).getDrivingInsights(transportId)
if (drivingInsights != null) {
    val event = drivingInsights.transportEvent
    val safetyScores = drivingInsights.safetyScores

    print("Focus score: ${safetyScores.focusScore}")
    print("Legal score: ${safetyScores.legalScore}")
    print("Smooth score: ${safetyScores.smoothScore}")
    print("Call-while-moving score: ${safetyScores.callWhileMovingScore}")
    print("Overall score: ${safetyScores.overallScore}")

    print("Event ID: ${event.id}")
    print("Started on: ${event.startTime}")
    print("Ended on: ${event.endTime}")
    print("Mode: ${event.transportMode}")

    if (event.distanceInMeters != null) {
        print("Distance: ${event.distanceInMeters}")
    }

    print("Waypoints: ${event.waypoints}")
}
import SentianceDrivingInsights from "@sentiance-react-native/driving-insights";

const drivingInsights = await SentianceDrivingInsights.getDrivingInsights(transportId);

if (drivingInsights !== null) {
    const event = drivingInsights.transportEvent; 
    const safetyScores = drivingInsights.safetyScores;
    
    if (safetyScores.focusScore) {
        console.log(`Focus score: ${safetyScores.focusScore}`);
    }
    if (safetyScores.legalScore) {
        console.log(`Legal score: ${safetyScores.legalScore}`);
    }
    if (safetyScores.smoothScore) {
        console.log(`Smooth score: ${safetyScores.smoothScore}`);
    }
    if (safetyScores.callWhileMovingScore) {
        console.log(`Call-while-moving score: ${safetyScores.callWhileMovingScore}`);
    }
    if (safetyScores.overallScore) {
        console.log(`Overall score: ${safetyScores.overallScore}`);
    }
    
    console.log(`Event ID: ${event.id}`);
    console.log(`Started on: ${event.startTime}`);
    console.log(`Ended on: ${event.endTime}`);
    console.log(`Mode: ${transport.transportMode}`);
    
    if (event.distance) {
        console.log(`Distance: ${event.distance}`);
    }
    console.log(`Waypoints: ${JSON.stringify(event.waypoints)}`);
}
import 'package:sentiance_driving_insights/sentiance_driving_insights.dart';

final sentianceDrivingInsights = SentianceDrivingInsights();

void getDrivingInsightsForTransport() async {
  String transportId = "your_transport_id";
  final drivingInsights = await sentianceDrivingInsights.getDrivingInsights(transportId);
  if (drivingInsights != null) {
    final transportEvent = drivingInsights.transportEvent;
    final safetyScores = drivingInsights.safetyScores;
    
    print('Focus score: ${safetyScores.focusScore}');
    print('Legal score: ${safetyScores.legalScore}');
    print('Smooth score: ${safetyScores.smoothScore}');
    print('Call-while-moving score: ${safetyScores.callWhileMovingScore}');
    print('Overall score: ${safetyScores.overallScore}');

    print('Event ID: ${transportEvent.id}');
    print('Started on: ${transportEvent.startTimeMs}');
    print('Ended on: ${transportEvent.endTimeMs}');
    print('Last updated on: ${transportEvent.lastUpdateTimeMs}');
    print('Mode: ${transportEvent.transportMode}');
    print('Duration in seconds: ${transportEvent.durationInSeconds}');
    print('Distance: ${transportEvent.distance}');
    print('Waypoints: [${transportEvent.waypoints.map((wp) => wp.toString()).join(", ")}]');
  }
}

Subscribe for Driving Insights Updates

public class DrivingInsightsUpdateReceiver: DrivingInsightsReadyDelegate {
    func subscribe() {
        Sentiance.shared.drivingInsightsReadyDelegate = self
    }
    
    public func onDrivingInsightsReady(insights: DrivingInsights) {
        // Handle the insights here (see the Query for Driving Insights
        // example above).
    }
}
DrivingInsightsApi.getInstance(context)
  .setDrivingInsightsReadyListener { insights -> 
    // Handle the insights here (see the Query for Driving Insights
    // example above).
}
import SentianceDrivingInsights from "@sentiance-react-native/driving-insights";

const subscription = await SentianceDrivingInsights.addDrivingInsightsReadyListener(drivingInsights => {
    // Handle the insights here (see the Query for Driving Insights
    // example above).
});

Create a background.dart file under your project's lib folder with the following code:

background.dart
import 'package:sentiance_driving_insights/sentiance_driving_insights.dart';

@pragma('vm:entry-point')
void registerDrivingInsightsListener() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  SentianceDrivingInsights.registerDrivingInsightsListener((drivingInsights) {
    // Handle the insights here (see the Query for Driving Insights
    // example above).
  });
}

Add the following code, depending on your target platform.

For iOS, add the following to your app delegate class:

AppDelegate.swift
import Flutter
import sentiance_driving_insights

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
    
        // Other code
        
        SentianceDrivingInsightsPlugin.initializeListener(
            withEntryPoint: "registerDrivingInsightsListener",
            libraryURI: "package:your_app_package_name/background.dart"
        )
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}

For Android, add this code to your custom application class:

MainApplication.kt
import android.app.Application
import com.sentiance.driving_insights_plugin.DrivingInsightsPlugin

class MainApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        
        // Other code

        val dartLibrary = "package:your_app_package_name/background.dart"
        DrivingInsightsPlugin.initializeListener(this, dartLibrary, "registerDrivingInsightsListener")
    }
}


Query For Driving Events

// Harsh driving events, used for computing the smooth driving score
Sentiance.shared.getHarshDrivingEvents(forTransportId: transportId).forEach { harshDrivingEvent in
    print("Start date: \(harshDrivingEvent.startDate)")
    print("End date: \(harshDrivingEvent.endDate)")
    print("Magnitude: \(harshDrivingEvent.magnitude)")
}

// Phone usage events, used for computing the focused driving score
Sentiance.shared.getPhoneUsageEvents(forTransportId: transportId).forEach { phoneUsageEvent in
    print("Start date: \(phoneUsageEvent.startDate)")
    print("End date: \(phoneUsageEvent.endDate)")
}

// Call-while-moving events, used for computing the call-while-moving score
Sentiance.shared.getCallsWhileMovingEvents(forTransportId: transportId).forEach { callWhileMovingEvent in
    print("Start date: \(callWhileMovingEvent.startDate)")
    print("End date: \(callWhileMovingEvent.endDate)")
    if let minSpeed = callWhileMovingEvent.minTraveledSpeedInMps?.floatValue {
        print("Min traveled speed: \(minSpeed)")
    }
    if let maxSpeed = callWhileMovingEvent.maxTraveledSpeedInMps?.floatValue {
        print("Max traveled speed: \(maxSpeed)")
    }
}

// Speeding events, used for computing the legal driving score
Sentiance.shared.getSpeedingEvents(forTransportId: transportId).forEach { speedingEvent in
    print("Start Date: \(speedingEvent.startDate)")
    print("End Date: \(speedingEvent.endDate)")
    print("Waypoints: \(speedingEvent.waypoints)")
}
// Harsh driving events, used for computing the smooth driving score
DrivingInsightsApi.getInstance(context).getHarshDrivingEvents(transportId)
  .forEach { harshDrivingEvent -> 
    print("Start time: ${harshDrivingEvent.startTime}")
    print("End time: ${harshDrivingEvent.endTime}")
    print("Magnitude: ${harshDrivingEvent.magnitude}")
}

// Phone usage events, used for computing the focused driving score
DrivingInsightsApi.getInstance(context).getPhoneUsageEvents(transportId)
  .forEach { phoneUsageEvent ->
    print("Start time: ${phoneUsageEvent.startTime}")
    print("End time: ${phoneUsageEvent.endTime}")
}

// Call-while-moving events, used for computing the call-while-moving score
DrivingInsightsApi.getInstance(context).getCallWhileMovingEvents(transportId)
  .forEach { callWhileMovingEvent ->
    print("Start time: ${callWhileMovingEvent.startTime}")
    print("End time: ${callWhileMovingEvent.endTime}")
    print("Min traveled speed: ${callWhileMovingEvent.minTraveledSpeedInMps}")        
    print("Max traveled speed: ${callWhileMovingEvent.maxTraveledSpeedInMps}")        
}

// Speeding events, used for computing the legal driving score
DrivingInsightsApi.getInstance(context).getSpeedingEvents(transportId)
  .forEach { speedingEvent ->
    print("Start time: ${speedingEvent.startTime}")
    print("End time: ${speedingEvent.endTime}")
    print("Waypoints: ${speedingEvent.waypoints}")
}
import SentianceDrivingInsights from "@sentiance-react-native/driving-insights";

// Harsh driving events, used for computing the smooth driving score
const harshDrivingEvents = await SentianceDrivingInsights.getHarshDrivingEvents(transportId);
for (const event of harshDrivingEvents) {
    console.log(`Start time: ${event.startTime}`);
    console.log(`End time: ${event.endTime}`);
    console.log(`Magnitude: ${event.magnitude}`);
}

// Phone usage events, used for computing the focused driving score
const phoneUsageEvents = await SentianceDrivingInsights.getPhoneUsageEvents(transportId);
for (const event of phoneUsageEvents) {
    console.log(`Start time: ${event.startTime}`);
    console.log(`End time: ${event.endTime}`);
}

// Call-while-moving events, used for computing the call-while-moving score
const callWhileMovingEvents = await SentianceDrivingInsights.getCallWhileMovingEvents(transportId);
for (const event of callWhileMovingEvents) {
    console.log(`Start time: ${event.startTime}`);
    console.log(`End time: ${event.endTime}`);
    console.log(`Min traveled speed: ${event.minTravelledSpeedInMps}`);        
    console.log(`Max traveled speed: ${event.maxTravelledSpeedInMps}`);
}

// Speeding events, used for computing the legal driving score
const speedingEvents = await SentianceDrivingInsights.getSpeedingEvents(transportId);
for (const event of speedingEvents) {
    console.log(`Start time: ${event.startTime}`);
    console.log(`End time: ${event.endTime}`);
    console.log(`Waypoints: ${JSON.stringify(event.waypoints)}`);
}
import 'package:sentiance_driving_insights/sentiance_driving_insights.dart';

final sentianceDrivingInsights = SentianceDrivingInsights();

void fetchDrivingEvents(String transportId) async {
  // Harsh driving events, used for computing the smooth driving score
  final harshDrivingEvents = await sentianceDrivingInsights.getHarshDrivingEvents(transportId);
  for (final event in harshDrivingEvents) {
    print('Start time: ${event.startTimeMs}');
    print('End time: ${event.endTimeMs}');
    print('Magnitude: ${event.magnitude}');
  }

  // Phone usage events, used for computing the focused driving score
  final phoneUsageEvents = await sentianceDrivingInsights.getPhoneUsageEvents(transportId);
  for (final event in phoneUsageEvents) {
    print('Start time: ${event.startTimeMs}');
    print('End time: ${event.endTimeMs}');
  }

  // Call-while-moving events, used for computing the call-while-moving score
  final callWhileMovingEvents = await sentianceDrivingInsights.getCallWhileMovingEvents(transportId);
  for (final event in callWhileMovingEvents) {
    print('Start time: ${event.startTimeMs}');
    print('End time: ${event.endTimeMs}');
    print('Min traveled speed: ${event.minTraveledSpeedInMps}');
    print('Max traveled speed: ${event.maxTraveledSpeedInMps}');
  }

  // Speeding events, used for computing the legal driving score
  final speedingEvents = await sentianceDrivingInsights.getSpeedingEvents(transportId);
  for (final event in speedingEvents) {
    print('Start time: ${event.startTimeMs}');
    print('End time: ${event.endTimeMs}');
    print('Waypoints: ${event.waypoints}');
  }
}
this page