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 the User's Current Context
  • Subscribe for User Context Updates
  1. Important topics
  2. SDK
  3. How To

Utilize the User Context API

PreviousUtilize the Driving Insights APINextUtilize the Smart Geofences 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 the user's current context, and how to register to receive real time updates in your app, as the user's context changes.

Query for the User's Current Context

Sentiance.shared.requestUserContext { context, error in
    guard let context = context else {
        print("Error: \(error?.failureReason)")
        return
    }
    
    print("Recent events:")
    
    // Print the recent events
    context.events.forEach({ event in
        print("Event ID: \(event.eventId)")
        print("Started on: \(event.startDate)")
        print("Ended on: \(event.endDate)")
        
        if event.type == .inTransport {
            let transport =  event as! SENTTransportEvent
            
            print("Type: transport")
            print("Mode: \(toStringMode(transport.transportMode))")
            
            if let distance = transport.distanceInMeters {
                print("Distance: \(distance)")
            }
            
            print("Waypoints: \(transport.waypoints)")
            
        }
        else if event.type == .stationary {
            let stationary =  event as! SENTStationaryEvent
            
            print("Type: stationary")
            print("Location: \(stationary.location)")
            print("Venue: \(stationary.venue)")
        }
        else if event.type == .offTheGrid {
            print("Type: off-the-grid")
        }
        else {
            print("Type: unknown")
        }
        
        print("")
    })
    
    // Print the home & work locations, semantic time, and last known location
    print("Home venue: \(context.home)")
    print("Work venue: \(context.work)")
    print("Semantic time: \(toString(context.semanticTime))")
    print("Last known location: \(context.lastKnownLocation)")
    
    // Print the user's active segments
    print("Active segments:")
    
    context.activeSegments.forEach { segment in
        print("  Category: \(toString(segment.category))")
        print("  Subcategory: \(toString(segment.subcategory))")
        print("  Type: \(toString(segment.type))")
        print("  Start date: \(toString(segment.startDate))")
        print("  End date: \(toString(segment.endDate))")
        
        print("  Attributes: ")
        segment.attributes.forEach { attribute in
            print("    \(attribute.name): \(attribute.value)")
        }
    }
}
UserContextApi.getInstance(context).requestUserContext()
    .addOnFailureListener { error ->
        print ("User context retrieval failed with reason ${error.reason}")
    }
    .addOnSuccessListener { context ->

        // Print the recent events
        print("Recent events:")

        context.events.forEach { event ->
            print("Event ID: ${event.id}")
            print("Started on: ${event.startTime}")
            print("Ended on: ${event.endTime}")

            when (event.eventType) {
                EventType.IN_TRANSPORT -> {
                    val transport = event as TransportEvent!

                    print("Type: transport")
                    print("Mode: ${transport.transportMode}")

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

                    print("Waypoints: ${transport.waypoints}")
                }
                EventType.STATIONARY -> {
                    val stationary = event as StationaryEvent!

                    print("Type: stationary")
                    print("Location: ${stationary.location}")
                    print("Venue: ${stationary.venue}")
                }
                EventType.OFF_THE_GRID -> {
                    print("Type: off-the-grid")
                }
                else -> {
                    print("Type: unknown")
                }
            }
        }

        // Print the home & work locations, semantic time, and last known location
        print("Home venue: ${context.home}")
        print("Work venue: ${context.work}")
        print("Semantic time: ${context.semanticTime}")
        print("Last known location: ${context.lastKnownLocation}")

        // Print the user's active segments
        print("Active segments:")

        context.activeSegments.forEach { segment ->
            print("  Category: ${segment.category}")
            print("  Subcategory: ${segment.subcategory}")
            print("  Type: ${segment.type}")
            print("  Start date: ${segment.startTime}")
            print("  End date: ${segment.endTime}")

            print("  Attributes: ")
            segment.attributes.forEach { attribute ->
                print("    ${attribute.name}: ${attribute.value}")
            }
        }
    }
import SentianceUserContext from '@sentiance-react-native/user-context';

const context = await SentianceUserContext.requestUserContext();

// Print the recent events
for (const event of context.events) {
    console.log(`Event ID: ${event.id}`);
    console.log(`Started on: ${event.startTime}`);
    console.log(`Ended on: ${event.endTime}`);

    switch (event.type) {
        case 'IN_TRANSPORT':
            const transport = event;
            console.log('Type: transport');
            console.log(`Mode: ${transport.transportMode}`);

            if (transport.distance) {
                console.log(`Distance: ${transport.distance}`);
            }
            console.log(`Waypoints: ${JSON.stringify(transport.waypoints)}`);
            break;
        case 'STATIONARY':
            const stationary = event;
            console.log('Type: stationary');
            console.log(`Location: ${JSON.stringify(stationary.location)}`);
            console.log(`Venue: ${JSON.stringify(stationary.venue)}`);
            break;
        case 'OFF_THE_GRID':
            console.log('Type: off-the-grid');
            break;
        default:
            console.log('Type: unknown');
    }
}

// Print the home & work locations, semantic time, and last known location
console.log(`Home venue: ${JSON.stringify(context.home)}`)
console.log(`Work venue: ${JSON.stringify(context.work)}`)
console.log(`Semantic time: ${context.semanticTime}`)
console.log(`Last known location: ${JSON.stringify(context.lastKnownLocation)}`)

// Print the user's active segments
console.log('Active segments:')

for (const segment of context.activeSegments) {
    console.log(`  ID: ${segment.id}`)
    console.log(`  Category: ${segment.category}`)
    console.log(`  Subcategory: ${segment.subcategory}`)
    console.log(`  Type: ${segment.type}`)
    console.log(`  Start date: ${segment.startTime}`)
    console.log(`  End date: ${segment.endTime}`)

    console.log('  Attributes:')
    segment.attributes.forEach { attribute ->
        console.log(`    ${attribute.name}: ${attribute.value}`)
    }
}
import 'package:sentiance_user_context/sentiance_user_context.dart';
import 'package:sentiance_event_timeline/sentiance_event_timeline.dart';

final sentianceUserContext = SentianceUserContext();

void fetchUserContext() async {
  final context = await sentianceUserContext.requestUserContext();

  // Print the recent events
  for (final event in context.events) {
    print('Event ID: ${event.id}');
    print('Started on: ${event.startTimeMs}');
    print('Ended on: ${event.endTimeMs}');

    if (event is TransportEvent) {
      final transport = event;
      print('Type: transport');
      print('Mode: ${transport.transportMode}');
      print('Distance: ${transport.distance}');
      print('Waypoints: ${transport.waypoints}');
    } else if (event is StationaryEvent) {
      print('Type: stationary');
      print('Location: ${event.location}');
      print('Venue: ${event.venue}');
    } else if (event is OffTheGridEvent) {
      print('Type: off-the-grid');
    } else if (event is UnknownEvent) {
      print('Type: unknown');
    }
  }

  // Print the home & work locations, semantic time, and last known location
  print('Home venue: ${context.home}');
  print('Work venue: ${context.work}');
  print('Semantic time: ${context.semanticTime}');
  print('Last known location: ${context.lastKnownLocation}');

  // Print the user's active segments
  print('Active segments:');

  for (final segment in context.activeSegments) {
    print('  ID: ${segment.segmentId}');
    print('  Category: ${segment.category}');
    print('  Subcategory: ${segment.subcategory}');
    print('  Type: ${segment.type}');
    print('  Start date: ${segment.startTimeMs}');
    print('  End date: ${segment.endTimeMs}');

    print('  Attributes:');
    for (final attribute in segment.attributes.nonNulls) {
      print('    ${attribute.name}: ${attribute.value}');
    }
  }
}

Subscribe for User Context Updates

public class UserContextHandler: SENTUserContextDelegate {
    
    public func subscribe() {
        Sentiance.shared.userContextDelegate = self
    }    
        
    public func didUpdate(_ userContext: SENTUserContext, 
       forCriteriaMask criteriaMask: SENTUserContextUpdateCriteria) {
        
        // Check the updated criteria
        if criteriaMask.contains(.currentEvent) {
            print("The user's current event was updated")
        }
        if criteriaMask.contains(.visitedVenues) {
            print("The user's visited venue information was updated")
        }
        if criteriaMask.contains(.activeSegments) {
            print("The user's active segments were updated")
        }
       
        // Handle the updated context data (see the Query for the 
        // User's Current Context example above)
    }
}
UserContextApi.getInstance(context)
  .addUserContextUpdateListener { criteria, context ->
    // Check the updated criteria
    if (criteria.contains(UserContextUpdateCriteria.CURRENT_EVENT)) {
        print("The user's current event was updated")
    }
    if (criteria.contains(UserContextUpdateCriteria.VISITED_VENUES)) {
        print("The user's visited venue information was updated")
    }
    if (criteria.contains(UserContextUpdateCriteria.ACTIVE_SEGMENTS)) {
        print("The user's active segments were updated")
    }

    // Handle the updated context data (see the Query for the
    // User's Current Context example above)
}
import {addUserContextUpdateListener} from "@sentiance-react-native/user-context";

const subscription = addUserContextUpdateListener(userContext => {
    // Handle the updated context data (see the Query for the
    // User's Current Context example above)
});

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

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

@pragma('vm:entry-point')
void registerUserContextListener() async {
  WidgetsFlutterBinding.ensureInitialized();

  SentianceUserContext.registerUserContextUpdateListener((criteria, context) {
    // Check the updated criteria
    if (criteria.contains(UserContextUpdateCriteria.currentEvent)) {
      print("The user's current event was updated");
    }
    if (criteria.contains(UserContextUpdateCriteria.visitedVenues)) {
      print("The user's visited venue information was updated");
    }
    if (criteria.contains(UserContextUpdateCriteria.activeSegments)) {
      print("The user's active segments were updated");
    }

    // Handle the updated context data (see the Query for the
    // User's Current Context 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_user_context

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
    
        // Other code
        
        SentianceUserContextPlugin.initializeListener(
            withEntryPoint: "registerUserContextListener",
            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.user_context_plugin.UserContextPlugin

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

        val dartLibrary = "package:your_app_package_name/background.dart"
        UserContextPlugin.initializeListener(this, dartLibrary, "registerUserContextListener")
    }
}
this page