Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

Docs

Analytics-Kotlin (Android)

Community x
Maintenance x
Flagship ✓

Flagship libraries offer the most up-to-date functionality on Segment’s most popular platforms. Segment actively maintains flagship libraries, which benefit from new feature releases and ongoing development and support.


On this page


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.

You can choose to set up yourAnalytics Kotlin source onmobile or on theserver. Segment doesn’t support device-mode destinations on the server-side.

If you’re migrating to Analytics Kotlin from a different mobile library, you can skip to themigration guide.

Benefits of Analytics Kotlin

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

Stability

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.

Performance

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

Developer Experience

Analytics Kotlin adds several improvements to the overall experience of using the core SDK, as well as improvements to the overallPlugin 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

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 aboutDestination Filters on Mobile, andEdge Functions on Mobile.

Getting started

To get started with the Analytics-Kotlin mobile library:

  1. Create a Source in Segment.
    1. Go toConnections > Sources > Add Source.
    2. Search forKotlin (Android) and clickAdd 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 throughMaven Central. 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’sreleases page.


    Kotlin

    repositories{mavenCentral()}dependencies{implementation'com.segment.analytics.kotlin:android:<latest_version>'}


    Java

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


    Kotlin

    // Add required importsimportcom.segment.analytics.kotlin.android.Analyticsimportcom.segment.analytics.kotlin.core.*// Create an analytics client with the given application context and Segment write key.// NOTE: in android, application context is required to pass as the second parameter.Analytics("YOUR_WRITE_KEY",applicationContext){// Automatically track Lifecycle eventstrackApplicationLifecycleEvents=trueflushAt=3flushInterval=10}


    Java

    AndroidAnalyticsKt.Analytics(BuildConfig.SEGMENT_WRITE_KEY,getApplicationContext(),configuration->{configuration.setFlushAt(1);configuration.setCollectDeviceId(true);configuration.setTrackApplicationLifecycleEvents(true);configuration.setTrackDeepLinks(true);//...other config optionsreturnUnit.INSTANCE;JavaAnalyticsanalyticsCompat=newJavaAnalytics(analytics);});

    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
    writeKeyrequiredThis is your Segment write key.
    applicationDefault set tonull.
    The application specific object (in the case ofAndroid: ApplicationContext).
    apiHostDefault set toapi.segment.io/v1.
    This sets a default API Host to which Segment sends events.
    cdnHostDefault set tocdn-settings.segment.com/v1.
    This sets a default CDN Host from which Segment retrieves settings.
    autoAddSegmentDestinationDefault set totrue.
    This automatically adds the Segment Destination plugin. You can set this tofalse if you want to manually add the Segment Destination plugin.
    collectDeviceIdDefault set tofalse.
    Set totrue to automatically collect the device Id.
    TheDRM API 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 ownplugin
    defaultSettingsDefault set to{}.
    The settings object used as fallback in case of network failure.
    flushAtDefault set to20.
    The count of events at which Segment flushes events.
    flushIntervalDefault set to30 (seconds).
    The interval in seconds at which Segment flushes events.
    flushPoliciesundefined
    Add more granular control for when to flush
    recordScreenViewsDefault set tofalse.
    Set totrue to automatically trigger screen events on Activity Start.
    storageProviderDefault set toConcreteStorageProvider.
    In Android, this must be set toAndroidStorageProvider. TheAnalytics constructors configure this automatically.
    trackApplicationLifecycleEventsDefault set tofalse.
    Set totrue to automatically track Lifecycle events.
    trackDeepLinksDefault set tofalse.
    Set totrue to automatically track opened Deep Links based on intents.
    useLifecycleObserverDefault set tofalse.
    Set totrue to useLifecycleObserver to track Application lifecycle events.
  4. Add Permissions toAndroidManifest.xml.

    Add these permissions to yourAndroidManifest.xml:

    <!--Requiredforinternet.--><uses-permissionandroid:name="android.permission.INTERNET"/><uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
  5. Enable Java 8+ API desugaring.

    If you’re on a version prior to1.10.4, the SDK internally uses a number of Java 8 language APIs through desugaring, which requires you to eitherenable desugaring, have a minimum API level of 26, or upgrade to the latest version. If you’re on version1.10.4 and above, you don’t need desugaring.

You’ll find configuration options such as IDFA collection and automatic screen tracking in Segment’sPlugin Examples repository.

Tracking methods

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

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

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 SegmentDestination docs.

Tools and extensions

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

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

Telemetry

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 settingTelemetry.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 settingTelemetry.sendWriteKeyOnError = false.

Timestamps in Kotlin

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

This page was last modified: 21 Aug 2025


Need support?

Questions? Problems? Need more info? Contact Segment Support for assistance!

Help improve these docs!

Was this page helpful?


Get started with Segment

Segment is the easiest way to integrate your websites & mobile apps data to over 300 analytics and growth tools.
or
Create free account

Was this page helpful?


[8]ページ先頭

©2009-2025 Movatter.jp