# 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. Declare any 3rd party plugins that you intend to make use of within the body of the Dart callback you defined on step #1

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 %}
{% endstep %}

{% step %}

### Declare 3rd party plugins

Chances are, your app has other dependencies than just the Sentiance SDKs.&#x20;

In case you needed to use a certain dependency/plugin (⚠️ **including any Sentiance plugin** ⚠️) inside the `registerEventTimelineListener` callback you previously defined, you need to let the Sentiance SDK know so that we make its usage possible for you. Without it, you will not be able to utilize other plugins inside the Dart callback.

Consider the example below:

{% 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 calls on line **9**, **14**, and **15** will fail unless you register the [**sqflite**](https://pub.dev/packages/sqflite), [**core**](https://pub.dev/packages/sentiance_core) and [**event timeline**](https://pub.dev/packages/sentiance_event_timeline) plugins respectively. To do that, update your native code accordingly:

{% 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 ->
            // flutterEngine is the environment where your Dart callback runs
            flutterEngine.plugins.apply {
                add(SqflitePlugin())
                add(CorePlugin())
                add(EventTimelinePlugin())
                // add here any other 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
            // flutterEngine is the environment where your Dart callback runs
            SqflitePlugin.register(with: flutterEngine.registrar(forPlugin: "sqflite")!)
            SentianceCorePlugin.register(with: flutterEngine.registrar(forPlugin: "core")!)
            SentianceEventTimelinePlugin.register(with: flutterEngine.registrar(forPlugin: "event_timeline")!)
        }
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}
```

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

You can also choose to register all the plugins of your app instead, if that would be more practical:

{% 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
            
            // The GeneratedPluginRegistrant class is generated by the Flutter tool
            // and allows you to register all of your app's plugins with a single flutter engine
            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
            // available under the GeneratedPluginRegistrant.h header file, and
            // allows you to register all of your app's plugins with a single flutter engine
            GeneratedPluginRegistrant.register(with: flutterEngine)
        }
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}
```

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

That's it. Your listener is now set up to get timeline event updates from the Sentiance SDK in the background, and can work side-by-side with other plugins that your app requires.
{% endstep %}
{% endstepper %}


---

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