# 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:

{% tabs %}
{% tab title="iOS" %}

```swift
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)
}
```

{% endtab %}

{% tab title="Android" %}

```kotlin
val from = Date(0)
val to = Date(Long.MAX_VALUE)

EventTimelineApi.getInstance(context).getTimelineEvents(from, to).forEach { event ->
    print("Event ID: ${event.id}")
}
```

{% endtab %}

{% tab title="React Native" %}

```javascript
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}`);
}
```

{% endtab %}

{% tab title="Flutter" %}

```dart
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}");
}
```

{% endtab %}
{% endtabs %}

Similarly, you can request various insights. Read through the [full example](/important-topics/sdk/howto/utilize-the-event-timeline-api.md) and explore [SDK API Reference](/important-topics/sdk/api-reference.md) for a comprehensive list of available APIs

### Listening to Callbacks for Real-time Updates

When setting up callbacks for real-time updates, it's crucial to ensure that you attach the listener at the appropriate location in your code.

The listeners should be included in the app boot-up scripts, right after executing the SDK initialization commands.

Below is an example of how to listen to *TimelineEvent* updates in real-time:

{% tabs %}
{% tab title="iOS" %}

```swift
//  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)
    }
}
```

{% endtab %}

{% tab title="Android" %}

```kotlin
// 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)  // <-------
        }
    }
}
```

{% endtab %}

{% tab title="React Native" %}

```javascript
listenForUpdates(); // Start listening to event updates

async function listenForUpdates() {
        await EventTimelineApi.addTimelineUpdateListener((event) => {
                console.log(event.eventId) // <---------
        });
}
```

{% endtab %}

{% tab title="Flutter" %}
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:

{% code title="background.dart" %}

```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()}");
    }
  }
}
```

{% endcode %}

## 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:

```kotlin
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:

```swift
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)
    }
}
```

{% endtab %}
{% endtabs %}

### 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.

{% tabs %}
{% tab title="iOS" %}
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.
{% endtab %}

{% tab title="Android" %}
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.
{% endtab %}

{% tab title="React Native" %}
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.

```javascript
// 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()
```

{% endtab %}

{% tab title="Flutter" %}
To handle background detections efficiently, make sure to setup/register your listeners appropriately in your Dart + native code as outlined in the previous section.
{% endtab %}
{% endtabs %}

Additional helpful links:

* [SDK API Reference](/important-topics/sdk/api-reference.md)
* [More On-Device How-to Guides](/important-topics/sdk/howto.md)
* [On Device features](/important-topics/sdk/appendix/on-device-features.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.sentiance.com/sentiance-insights/accessing-sentiance-insights/via-on-device-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
