Skip to contentSkip to navigationSkip to topbar
On this page
Looking for more inspiration?Visit the
(information)
You're in the right place! Segment documentation is now part of Twilio Docs. The content you are used to is still here—just in a new home with a refreshed look.

Analytics-Kotlin (Android)


Community x
Maintenance x
Flagship

With Analytics Kotlin, you can send data using Kotlin and Java applications to any analytics or marketing tool without having to learn, test, or implement a new API every time. Analytics Kotlin enables you to process and track the history of a payload, while Segment controls the API and prevents unintended operations.

(success)

Success!

You can choose to set up your Analytics Kotlin source on mobile or on the server. Segment doesn't support device-mode destinations on the server-side.

(warning)

Warning

If you're migrating to Analytics Kotlin from a different mobile library, you can skip to the migration guide.


Benefits of Analytics Kotlin

benefits-of-analytics-kotlin page anchor

Analytics Kotlin provides several key benefits including improvements in stability, performance, and developer experience when compared to Analytics Android (Classic).

Stability

stability page anchor

Analytics Kotlin uses thread-safety strategies to isolate Plugins, Device-Mode Destinations, and custom Middleware from the host app. By isolating these features from the host app we can protect the host app from any potential problems including Exceptions that would otherwise terminate the host app.

Analytics Kotlin is a leap forward in terms of performance when compared to Analytics Android (Classic):

  • Faster event processing and delivery
  • Significantly lower CPU usage
  • Small memory & disk usage footprint

Analytics Kotlin adds several improvements to the overall experience of using the core SDK, as well as improvements to the overall Plugin Architecture:

  • Ability to use Type Safe data structures rather than just dictionaries.
  • Simpler syntax and more developer friendly overall.
  • More customization options than ever before.

Device Mode Transformations & Filtering

device-mode-transformations--filtering page anchor

For the first time ever, developers can filter and transform their users' events even before the events leave the mobile device. What's more, these Filters & transformations can be applied dynamically (either via the Segment Dashboard, or via Javascript uploaded to the workspace) and do not require any app updates!

Learn more about Destination Filters(link takes you to an external page) on Mobile, and Edge Functions(link takes you to an external page) on Mobile.


To get started with the Analytics-Kotlin mobile library:

  1. Create a Source in Segment.

    1. Go to Connections > Sources > Add Source.
    2. Search for Kotlin (Android) and click Add source.
  2. Add the Analytics dependency to your build.gradle.

    Segment recommends you to install the library with a build system like Gradle, as it simplifies the process of upgrading versions and adding integrations. The library is distributed through Maven Central(link takes you to an external page). Add the analytics module to your build.gradle as a dependency as shown in the code sample below, and replace <latest_version> with the latest version listed on Segment's releases page.(link takes you to an external page)


    Kotlin

    1
    repositories {
    2
    mavenCentral()
    3
    }
    4
    dependencies {
    5
    implementation 'com.segment.analytics.kotlin:android:<latest_version>'
    6
    }


    Java

    1
    repositories {
    2
    mavenCentral()
    3
    }
    4
    dependencies {
    5
    implementation 'com.segment.analytics.kotlin:android:<latest_version>'
    6
    }
  3. Initialize and configure the client. Segment recommends you to install the client in your application subclass.


    Kotlin

    1
    // Add required imports
    2
    import com.segment.analytics.kotlin.android.Analytics
    3
    import com.segment.analytics.kotlin.core.*
    4
    5
    // Create an analytics client with the given application context and Segment write key.
    6
    // NOTE: in android, application context is required to pass as the second parameter.
    7
    Analytics("YOUR_WRITE_KEY", applicationContext) {
    8
    // Automatically track Lifecycle events
    9
    trackApplicationLifecycleEvents = true
    10
    flushAt = 3
    11
    flushInterval = 10
    12
    }


    Java

    1
    AndroidAnalyticsKt.Analytics(BuildConfig.SEGMENT_WRITE_KEY, getApplicationContext(), configuration -> {
    2
    3
    configuration.setFlushAt(1);
    4
    configuration.setCollectDeviceId(true);
    5
    configuration.setTrackApplicationLifecycleEvents(true);
    6
    configuration.setTrackDeepLinks(true);
    7
    //...other config options
    8
    9
    return Unit.INSTANCE;
    10
    11
    JavaAnalytics analyticsCompat = new JavaAnalytics(analytics);​
    12
    });

    Warning: If you're on an Android platform, you must add the application context as the second parameter.


    Automatically tracking lifecycle events (Application Opened, Application Installed, Application Updated) is optional, but Segment highly recommends you to configure these options in order to track core events. Unlike the Analytics Android SDK, the Analytics Kotlin SDK doesn't provide a singleton instance and relies on you to keep track of the instance.


    These are the options you can apply to configure the client:

    Option NameDescription
    writeKey requiredThis is your Segment write key.
    applicationDefault set to null.
    The application specific object (in the case of Android: ApplicationContext).
    apiHostDefault set to api.segment.io/v1.
    This sets a default API Host to which Segment sends events.
    cdnHostDefault set to cdn-settings.segment.com/v1.
    This sets a default CDN Host from which Segment retrieves settings.
    autoAddSegmentDestinationDefault set to true.
    This automatically adds the Segment Destination plugin. You can set this to false if you want to manually add the Segment Destination plugin.
    collectDeviceIdDefault set to false.
    Set to true to automatically collect the device Id.
    The DRM API(link takes you to an external page) generates the device ID. If the ID didn't generate previously (for example, because the app was newly installed), an empty string shows before the ID generation completes. You can overwrite the device ID with a custom ID by writing your own plugin
    defaultSettingsDefault set to {}.
    The settings object used as fallback in case of network failure.
    flushAtDefault set to 20.
    The count of events at which Segment flushes events.
    flushIntervalDefault set to 30 (seconds).
    The interval in seconds at which Segment flushes events.
    flushPoliciesundefined
    Add more granular control for when to flush
    recordScreenViewsDefault set to false.
    Set to true to automatically trigger screen events on Activity Start.
    storageProviderDefault set to ConcreteStorageProvider.
    In Android, this must be set to AndroidStorageProvider. The Analytics constructors configure this automatically.
    trackApplicationLifecycleEventsDefault set to false.
    Set to true to automatically track Lifecycle events.
    trackDeepLinksDefault set to false.
    Set to true to automatically track opened Deep Links based on intents.
    useLifecycleObserverDefault set to false.
    Set to true to use LifecycleObserver to track Application lifecycle events.
  4. Add Permissions to AndroidManifest.xml.

    Add these permissions to your AndroidManifest.xml:

    1
    <!-- Required for internet. -->
    2
    <uses-permission android:name="android.permission.INTERNET"/>
    3
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  5. Enable Java 8+ API desugaring.

    If you're on a version prior to 1.10.4, the SDK internally uses a number of Java 8 language APIs through desugaring, which requires you to either enable desugaring(link takes you to an external page), have a minimum API level of 26, or upgrade to the latest version. If you're on version 1.10.4 and above, you don't need desugaring.

(information)

Info

You'll find configuration options such as IDFA collection and automatic screen tracking in Segment's Plugin Examples repository(link takes you to an external page).


Once you've installed the mobile or server Analytics Kotlin library, you can start collecting data through Segment's tracking methods:

(information)

Info

For any of the different methods described, you can replace the properties and traits in the code samples with variables that represent the data collected.

Destinations are the business tools or apps that Segment forwards your data to. Adding Destinations allow you to act on your data and learn more about your customers in real time.


Segment offers support for two different types of destination connection modes: Cloud-mode and Device-mode. learn more about the differences between the two in the Segment Destination docs.


Analytics-Kotlin is built with extensibility in mind. Use the tools list below to improve data collection.

(warning)

Warning

If you are using the Analytics Android (Classic) SDK, you can find the documentation here. Many of the features available in the Analytics Kotlin SDK are not available in the Analytics Android (Classic) SDK.


The Analytics-Kotlin SDK collects telemetry data on configuration and usage by default. This includes basic information on SDK setup, plugins and event types used, and basic error details. Segment downsamples the data to minimize traffic and doesn't collect any personally identifiable information (PII) or event data.

You can disable telemetry at any time by setting Telemetry.enable = false.

When internal errors or errors from plugins occur, the write key may be included with error data to help Segment identify the issue(s). You can disable this by setting Telemetry.sendWriteKeyOnError = false.


Due to efficiency updates made to Segment's Kotlin library, Segment now adds the sentAt timestamp to an event when the batch is complete and initially tried to the Segment API. This can impact the value of the timestamp field calculated by Segment if users are operating in an offline mode. More details on this change can be seen in Segment's timestamp documentation.