> For the complete documentation index, see [llms.txt](https://docs.sentiance.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sentiance.com/a-complete-integration/flutter-quick-start/registering-bg-listeners.md).

# 7. Registering background listeners

To register a background listener for the Sentiance SDK, you need to:

1. Define a callback in your Dart code.
2. Register your listener in your native code (once per every platform you support)
3. *(Optional)* Register any **non-Sentiance** plugins you use inside that Dart callback.

> **Sentiance plugins are registered automatically** with every background engine the SDK creates (available from SDK **v6.26.0**). If your Dart callback only calls Sentiance APIs, steps 1 and 2 are all you need. Continue to step 3 only when your callback also uses non-Sentiance plugins.

\
In the guide below, we will demonstrate how to register a background **event timeline** listener. Please note that the process is identical for the rest of the background listeners that the Sentiance SDKs provide.

{% stepper %}
{% step %}

## Define a Dart callback

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

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

```dart
import 'package:sentiance_event_timeline/sentiance_event_timeline.dart';

@pragma('vm:entry-point')
Future<void> registerEventTimelineListener() async {
  WidgetsFlutterBinding.ensureInitialized();
  debugPrint("Registering a new event timeline listener.");

  SentianceEventTimeline.registerEventTimelineUpdateListener((timelineEvent) {
    // Handle new timeline events here
    debugPrint("New timeline event: ${timelineEvent.toString()}");
  });
}
```

{% endcode %}
{% endstep %}

{% step %}

## Register listener in native code

Next, you need to make changes to your native code to ensure that your `registerEventTimelineListener` Dart callback can get updates from the Sentiance SDK when your app is running in the background.

{% tabs %}
{% tab title="if you're targeting Android" %}
Create an `Application` class (if you haven't already) and add the following code inside:

{% code title="MainApplication.kt" %}

```kotlin
import android.app.Application
import com.sentiance.event_timeline_plugin.EventTimelinePlugin

// Don't forget to update your app's manifest:
// <application android:name=".MainApplication" ...></application>
class MainApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        
        // Initialize the Sentiance SDK first
        val initResult = CorePlugin.initialize(this)
        
        // Replace '<your_app_package_name>' with the name of your app package
        // as shown inside your project's pubspec.yaml file
        val dartLibrary = "package:<your_app_package_name>/background.dart"
        // Make sure the callback name specified here matches the name of the 
        // callback you previously defined in your Dart code 
        val dartCallbackName = "registerEventTimelineListener"
        
        EventTimelinePlugin.initializeListener(
            context = this,
            dartEntryPointLibrary = dartLibrary,
            dartEntryPointFunctionName = dartCallbackName,
            includeProvisionalEvents = true
        )
    
        // Other code
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="if you're targeting iOS" %}
Add the following code inside your **AppDelegate.swift** file:

{% code title="AppDelegate.swift" %}

```swift
import Flutter
import UIKit
import sentiance_core
import sentiance_event_timeline

@main
@objc class AppDelegate: FlutterAppDelegate {

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        // other code
        
        let initResult = SentianceCorePlugin.shared.initialize()
        
        // Replace '<your_app_package_name>' with the name of your app package
        // as shown inside your project's pubspec.yaml file
        let libraryURI = "package:<your_app_package_name>/background.dart"
        let dartCallbackName = "registerEventTimelineListener"
        
        SentianceEventTimelinePlugin.initializeListener(
            withEntryPoint: dartCallbackName,
            libraryURI: libraryURI,
            includeProvisionalEvents: true
        )
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

> If your Dart callback only uses Sentiance APIs, you're done. Every Sentiance plugin your app depends on is registered automatically on the background engine, so you can call any Sentiance API from inside your listener. Continue to Step 3 only if your callback also uses non-Sentiance plugins.
> {% endstep %}

{% step %}

### Register non-Sentiance plugins (optional)

Sentiance plugins (such as `SentianceCore` and `SentianceEventTimeline`) are registered automatically on every background engine the SDK creates, so you do not need to register them yourself.

If your callback also uses **non-Sentiance** plugins, you must register those with the background engine through the registration callback on `initializeListener`. Without this step, those third party plugins won't be accessible inside your Dart callback.

Consider this example, where the callback uses both Sentiance plugins and the third party `sqflite` plugin:

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

```dart
import 'package:sentiance_core/sentiance_core.dart';
import 'package:sentiance_event_timeline/sentiance_event_timeline.dart';
import 'package:sqflite/sqflite.dart' as sqflite;

@pragma('vm:entry-point')
Future<void> registerEventTimelineListener() async {
  WidgetsFlutterBinding.ensureInitialized();

  final sqliteDatabase = sqflite.openDatabase(...);
  final corePlugin = SentianceCore();
  final eventTimelinePlugin = SentianceEventTimeline();

  SentianceEventTimeline.registerEventTimelineUpdateListener((timelineEvent) async {
    final userId = await corePlugin.getUserId();
    eventTimelinePlugin.setTransportTags({"tag": "value"});
  });
}
```

{% endcode %}

The Sentiance APIs above work out of the box. Only `sqflite` needs to be registered, as shown below.

{% tabs %}
{% tab title="Android" %}
{% code title="MainApplication.kt" %}

```kotlin
import android.app.Application
import com.sentiance.core_plugin.CorePlugin
import com.sentiance.event_timeline_plugin.EventTimelinePlugin
import com.tekartik.sqflite.SqflitePlugin

class MainApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        
        // Initialize the Sentiance SDK first
        val initResult = CorePlugin.initialize(this)
        
        val dartLibrary = "package:<your_app_package_name>/background.dart"
        val dartCallbackName = "registerEventTimelineListener"
        
        EventTimelinePlugin.initializeListener(
            context = this,
            dartEntryPointLibrary = dartLibrary,
            dartEntryPointFunctionName = dartCallbackName,
            includeProvisionalEvents = true
        ) { flutterEngine ->
            // Register only your non-Sentiance plugins here.
            // Sentiance plugins are registered automatically.
            flutterEngine.plugins.add(SqflitePlugin())
            // add here any other non-Sentiance plugin that you intend to use
        }
    
        // Other code
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="iOS" %}
{% code title="AppDelegate.swift" %}

```swift
import Flutter
import UIKit
import sentiance_core
import sentiance_event_timeline
import sqflite_darwin

@main
@objc class AppDelegate: FlutterAppDelegate {

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        // other code
        
        // Initialize the Sentiance SDK first
        let initResult = SentianceCorePlugin.shared.initialize()
        
        // Replace '<your_app_package_name>' with the name of your app package
        // as shown inside your project's pubspec.yaml file
        let libraryURI = "package:<your_app_package_name>/background.dart"
        let dartCallbackName = "registerEventTimelineListener"
        
        SentianceEventTimelinePlugin.initializeListener(
            withEntryPoint: dartCallbackName,
            libraryURI: libraryURI,
            includeProvisionalEvents: true
        ) { flutterEngine in
            // Register only your non-Sentiance plugins here.
            // Sentiance plugins are registered automatically.
            SqflitePlugin.register(with: flutterEngine.registrar(forPlugin: "sqflite")!)
        }
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

> **Recommended:** register only the specific non-Sentiance plugins your callback needs, as shown above. The SDK registers every Sentiance plugin for you, so listing them yourself is unnecessary.

#### Alternative: register everything at once (still supported)

If your app depends on many third party plugins, you can register all of them in one call with Flutter's `GeneratedPluginRegistrant` instead of adding each plugin individually.

This still works, but note that `GeneratedPluginRegistrant` registers *every* plugin in your app, including the Sentiance ones. The SDK detects that the Sentiance plugins are already being registered, skips the duplicate registration to avoid any conflict, and logs a warning for each one. For that reason we recommend the explicit approach above, which keeps the background-engine logs clean.

{% tabs %}
{% tab title="Android" %}
{% code title="MainApplication.kt" %}

```kotlin
import android.app.Application
import com.sentiance.core_plugin.CorePlugin
import com.sentiance.event_timeline_plugin.EventTimelinePlugin
import io.flutter.plugins.GeneratedPluginRegistrant

class MainApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        
        // Initialize the Sentiance SDK first
        val initResult = CorePlugin.initialize(this)
        
        val dartLibrary = "package:<your_app_package_name>/background.dart"
        val dartCallbackName = "registerEventTimelineListener"
        
        EventTimelinePlugin.initializeListener(
            context = this,
            dartEntryPointLibrary = dartLibrary,
            dartEntryPointFunctionName = dartCallbackName,
            includeProvisionalEvents = true
        ) { flutterEngine ->
              // flutterEngine is the environment where your Dart callback runs.
              //
              // GeneratedPluginRegistrant is generated by the Flutter tool and registers
              // every plugin your app depends on with a single flutter engine. Sentiance
              // plugins among them are already auto-registered, so the SDK skips them and
              // logs a warning for each.
              GeneratedPluginRegistrant.registerWith(flutterEngine)
        }
    
        // Other code
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="iOS" %}
{% code title="AppDelegate.swift" %}

```swift
import Flutter
import UIKit
import sentiance_core
import sentiance_event_timeline

@main
@objc class AppDelegate: FlutterAppDelegate {

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        // other code
        
        // Initialize the Sentiance SDK first
        let initResult = SentianceCorePlugin.shared.initialize()
        
        // Replace '<your_app_package_name>' with the name of your app package
        // as shown inside your project's pubspec.yaml file
        let libraryURI = "package:<your_app_package_name>/background.dart"
        let dartCallbackName = "registerEventTimelineListener"
        
        SentianceEventTimelinePlugin.initializeListener(
            withEntryPoint: dartCallbackName,
            libraryURI: libraryURI,
            includeProvisionalEvents: true
        ) { flutterEngine in
              // flutterEngine is the environment where your Dart callback runs.
              //
              // GeneratedPluginRegistrant is generated by the Flutter tool and registers
              // every plugin your app depends on with a single flutter engine. Sentiance
              // plugins among them are already auto-registered, so the SDK skips them and
              // logs a warning for each.
              GeneratedPluginRegistrant.register(with: flutterEngine)
        }
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

Your listener is now configured to receive timeline event updates from the Sentiance SDK in the background, with access to any non-Sentiance plugins you registered.
{% endstep %}
{% endstepper %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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/a-complete-integration/flutter-quick-start/registering-bg-listeners.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.
