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
  • Listen to smart geofence entry/exit events
  • Refresh the list of monitored geofences
  • Get the current smart geofences detection mode
  1. Important topics
  2. SDK
  3. How To

Utilize the Smart Geofences API

PreviousUtilize the User Context APINextTroubleshooting

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 register for real time smart geofence entry and exit event notifications, how to query the Sentiance SDK for the current smart geofences detection mode, as well as how to refresh the list of monitored smart geofences.

Listen to smart geofence entry/exit events

// Create an instance of the delegate that will handle the events.
private let smartGeofenceEventDelegate = MySmartGeofenceEventDelegate()

// Set the delegate on the Sentiance SDK. Note that the SDK holds a weak
// reference to this delegate.
Sentiance.shared.smartGeofenceEventsDelegate = smartGeofenceEventDelegate

// Define the delegate class that will handle the events.
class MySmartGeofenceEventDelegate: SmartGeofenceEventDelegate {
    func onSmartGeofenceEvent(_ smartGeofenceEvent: SmartGeofenceEvent) {
        // Handle the events here.
    }
}
import com.sentiance.sdk.smartgeofences.api.SmartGeofenceApi

SmartGeofenceApi.getInstance(mContext).setSmartGeofenceEventListener { event ->
    // Handle the events here.
}
import {addSmartGeofenceEventListener} from "@sentiance-react-native/smart-geofences";

const subscription = addSmartGeofenceEventListener(smartGeofenceEvent => {
    // Handle the events here.
});

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

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

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

  SentianceSmartGeofences.registerSmartGeofenceEventListener((smartGeofenceEvent) {
    // Handle the events here.
  });
}

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_smart_geofences

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {

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

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

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

Refresh the list of monitored geofences

The SDK regularly refreshes the list of monitored geofences. You can request an immediate refresh as follows:

Sentiance.shared.refreshSmartGeofences { result, error in
    if let result {
        print("Geofences refreshed")
    }
    if let error {
        print("Error happened with smart geofence refreshing:" + error.description)
    }
}
import com.sentiance.sdk.smartgeofences.api.SmartGeofenceApi

SmartGeofenceApi.getInstance(mContext).refreshGeofences()
    .addOnSuccessListener {
        Log.d(TAG, "Geofences refreshed")
    }.addOnFailureListener {
        Log.d(TAG, "Failed to refresh geofences. Error: ${it.reason}")
    }
import {refreshGeofences} from "@sentiance-react-native/smart-geofences";

try {
     await refreshGeofences();
     console.log('Geofences refreshed');
} catch (error) {
     const refreshError = error.userInfo;
     console.error('Failed to refresh geofences. Error: ' + refreshError.reason);
}
import 'package:sentiance_smart_geofences/sentiance_smart_geofences.dart';

final sentianceSmartGeofences = SentianceSmartGeofences();

void refreshGeofences() async {
  String result;

  try {
    await sentianceSmartGeofences.refreshGeofences();
    result = "Geofences refreshed successfully.";
  } on SmartGeofencesRefreshError catch (e) {
    result = "Failed to refresh geofences, reason: ${e.reason.name} - details: ${e.details}";
  } catch (e) {
    result = "An unexpected error occurred: $e";
  }

  print(result);
}

Get the current smart geofences detection mode

let detectionMode = Sentiance.shared.smartGeofenceDetectionMode
print("Detection mode is:" + String(describing: detectionMode))
val detectionMode = SmartGeofenceApi.getInstance(this).detectionMode
Log.d(TAG, "Detection mode is: $detectionMode")
import {getDetectionMode} from "@sentiance-react-native/smart-geofences";

const detectionMode = await getDetectionMode();
console.log('Detection mode is:', detectionMode);
import 'package:sentiance_smart_geofences/sentiance_smart_geofences.dart';

final sentianceSmartGeofences = SentianceSmartGeofences();

void getDetectionMode() async {
  final detectionMode = await sentianceSmartGeofences.getDetectionMode();
  print('Detection mode is: $detectionMode');
}
this page