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 Migration Guide


(information)

Setting up an Analytics-Android Source

This guide assumes you already have an Analytics-Android Source in your Segment workspace. If you need to create a new one, refer to the source Overview.

If you're using a previous Segment mobile library such as Analytics-Android, follow these steps to migrate to the Analytics-Kotlin library. Analytics-Kotlin is designed to work with your Java codebase as well.

  1. Import Analytics-Kotlin.
  2. Upgrade your Destinations.
  3. Advanced: Upgrade your Middleware.
  4. Upgrade Notes.

1. Import Analytics-Kotlin

1-import-analytics-kotlin page anchor

1. Add the dependencies to your app.

1-add-the-dependencies-to-your-app page anchor

In your top-level build.gradle:

1
repositories {
2
mavenCentral()
3
}

In your app module's build.gradle:

1
dependencies {
2
implementation 'com.segment.analytics.kotlin:android:<latest_version>'
3
}

You have now added Analytics-Kotlin to your project. You can remove the Analytics-Android SDK from your app.

2. Modify your initialized instance

2-modify-your-initialized-instance page anchor
KotlinJava
1
val analytics = Analytics("YOUR_WRITE_KEY", context) {
2
trackApplicationLifecycleEvents = true
3
}

3. Update your import statements

3-update-your-import-statements page anchor

You need to update the imports for Analytics-Kotlin.

Before example:

1
import com.segment.analytics.Analytics;
2
import com.segment.analytics.Middleware;

After example:

1
import com.segment.analytics.kotlin.core.Analytics;
2
import com.segment.analytics.kotlin.android.AndroidAnalyticsKt; // Only for calling from Android
3
import com.segment.analytics.kotlin.core.compat.JavaAnalytics; // Only for calling from Java
4
import com.segment.analytics.kotlin.core.platform.Plugin; // Replaces Middleware
(information)

Info

Analytics-Kotlin supports running multiple instances of the analytics object, so it does not assume a singleton. However, if you're migrating from Analytics-Android and all your track calls are routed to the Analytics.shared() singleton, you can these calls to your new Analytics-Kotlin object.

Add this extension to your code to ensure that tracking calls written for Analytics-Android work with Analytics-Kotlin.

1
2
// Application's onCreate
3
...
4
5
sharedAnalytics = Analytics(...)...
6
7
fun Analytics.with {
8
// TODO: Finish this
9
return MyApplication.sharedAnalytics; // or whatever variable name you're using
10
}

2. Upgrade your destinations

2-upgrade-your-destinations page anchor

If your app uses Segment to route data to Destinations via Segment-cloud (i.e. Cloud-mode destinations), you can skip this step. Analytics-Kotlin treats Device-mode Destinations as plugins, and simplifies the process in integrating them into your app. Analytics-Kotlin supports these Device-Mode Destinations with more to come.

1. Import the destination plugin

1-import-the-destination-plugin page anchor
implementation '<owner>:<project>:<version>'

2. Add plugin to your Analytics instance:

2-add-plugin-to-your-analytics-instance page anchor

Import the plugin:

import com.example.SomeDestinationPlugin

Add the pluging to the Analytics Instance:

JavaKotlin
analytics.add(new SomeDestinationPlugin());

Your events will now begin to flow to the added destination in Device-Mode.


3. Upgrade middleware to plugins

3-upgrade-middleware-to-plugins page anchor

Middlewares are a powerful mechanism that can augment events collected by the Analytics Android (Classic) SDK. A middleware is a simple function that is invoked by the Segment SDK and can be used to monitor, modify, augment or reject events. Analytics-Kotlin replaces the concept of middlewares with Enrichment Plugins to give you even more control over your event data. Refer to the Plugin Architecture Overview for more information.

1. Upgrading source middleware

1-upgrading-source-middleware page anchor

Before example:

JavaKotlin
1
builder
2
.useSourceMiddleware(new Middleware() {
3
@Override
4
public void intercept(Chain chain) {
5
// Get the payload.
6
BasePayload payload = chain.payload();
7
8
// Set the device year class on the context object.
9
int year = YearClass.get(getApplicationContext());
10
Map<String, Object> context = new LinkedHashMap<>(payload.context());
11
context.put("device_year_class", year);
12
13
// Build our new payload.
14
BasePayload newPayload = payload.toBuilder()
15
.context(context)
16
.build();
17
18
// Continue with the new payload.
19
chain.proceed(newPayload);
20
}
21
})

After example:

JavaKotlin
1
analytics.add(new Plugin() {
2
private Analytics analytics;
3
4
@Override
5
public BaseEvent execute(@NonNull BaseEvent event) {
6
// Set the device year class on the context object.
7
int year = YearClass.get(getApplicationContext());
8
EventTransformer.putInContext(event, "device_year_class", year);
9
return event;
10
}
11
12
@Override
13
public void setup(@NonNull Analytics analytics) {
14
setAnalytics(analytics);
15
}
16
17
@NonNull
18
@Override
19
public Type getType() {
20
return Plugin.Type.Enrichment;
21
}
22
23
@NonNull
24
@Override
25
public Analytics getAnalytics() {
26
return analytics;
27
}
28
29
@Override
30
public void setAnalytics(@NonNull Analytics analytics) {
31
this.analytics = analytics;
32
}
33
});

2. Upgrading destination middleware

2-upgrading-destination-middleware page anchor

If you don't need to transform all of your Segment calls, and only want to transform the calls going to specific, device-mode destinations, use Destination plugins.

Before example:


JavaKotlin
1
builder
2
.useDestinationMiddleware("Segment.io", new Middleware() {
3
@Override
4
public void intercept(Chain chain) {
5
// Get the payload.
6
BasePayload payload = chain.payload();
7
8
// Set the device year class on the context object.
9
int year = YearClass.get(getApplicationContext());
10
Map<String, Object> context = new LinkedHashMap<>(payload.context());
11
context.put("device_year_class", year);
12
13
// Build our new payload.
14
BasePayload newPayload = payload.toBuilder()
15
.context(context)
16
.build();
17
18
// Continue with the new payload.
19
chain.proceed(newPayload);
20
}
21
})

After example:


JavaKotlin
1
SegmentDestination segmentDestination = analytics.find(SegmentDestination.class);
2
3
segmentDestination.add(new Plugin() {
4
private Analytics analytics;
5
6
@Override
7
public BaseEvent execute(@NonNull BaseEvent event) {
8
// Set the device year class on the context object.
9
int year = YearClass.get(getApplicationContext());
10
EventTransformer.putInContext(event, "device_year_class", year);
11
return event;
12
}
13
14
@Override
15
public void setup(@NonNull Analytics analytics) {
16
setAnalytics(analytics);
17
}
18
19
@NonNull
20
@Override
21
public Type getType() {
22
return Plugin.Type.Enrichment;
23
}
24
25
@NonNull
26
@Override
27
public Analytics getAnalytics() {
28
return analytics;
29
}
30
31
@Override
32
public void setAnalytics(@NonNull Analytics analytics) {
33
this.analytics = analytics;
34
}
35
});

(information)

Call Identify as a one-off after migrating to Kotlin

To preserve the userId for users identified prior to your migration to Kotlin, you must make a one-off Identify call. This is due to a storage format change between the Analytics-Android and the Analytics-Kotlin libraries.

1. Changes to the configuration object

1-changes-to-the-configuration-object page anchor

The following option was renamed in Analytics-Kotlin:

BeforeAfter
contextName changed to application
defaultAPIHostName changed to apiHost
defaultProjectSettingsName changed to defaultSettings
experimentalUseNewLifecycleMethodsName changed to useLifecycleObserver

The following option was added in Analytics-Kotlin:

Added optionDetails
autoAddSegmentDestinationThe analytics client automatically adds the Segment Destination. Set this to false, if you want to customize the initialization of the Segment Destination, such as, add destination middleware).


The following option was removed in Analytics-Kotlin:

Removed optionDetails
defaultOptionsRemoved in favor of a plugin that adds the default data to the event payloads. Segment doesn't provide a plugin example since it's dependent on your needs.
recordScreenViewsRemoved in favor of the AndroidRecordScreenPlugin that provides the same functionality.
trackAttributionDataThis feature no longer exists.

Properties have been replaced by JsonElement. Since Properties are essentially a Map<String, Object> we provide the ability to pass a map into our core tracking methods:

JavaKotlin
1
Map<String, Object> map = new HashMap<>();
2
map.put("feature", "chat");
3
Map<String, Object> miniMap = new HashMap<>();
4
miniMap.put("colorChoice", "green");
5
map.put("prefs", miniMap);
6
analytics.track("UseFeature", map);;

3. Options support removed

3-options-support-removed page anchor

Options are not supported and should be converted into plugins.

4. Traits are no longer attached to analytics.track() events automatically

4-traits-are-no-longer-attached-to-analyticstrack-events-automatically page anchor

To prevent sending unwanted or unnecessary PII, traits collected in analytics.identify() events are no longer automatically attached to analytics.track() events. To achieve this, you can write a before plugin:

1
import com.segment.analytics.kotlin.core.Analytics
2
import com.segment.analytics.kotlin.core.Plugin
3
import com.segment.analytics.kotlin.core.PluginType
4
import com.segment.analytics.kotlin.core.platform.Plugin
5
import com.segment.analytics.kotlin.core.events.RawEvent
6
7
class InjectTraits : Plugin {
8
9
override val type: PluginType = PluginType.Enrichment
10
var analytics: Analytics? = null
11
12
override fun <T : RawEvent> execute(event: T?): T? {
13
if (event?.type == "identify") {
14
return event
15
}
16
17
var workingEvent = event
18
val context = event?.context?.toMutableMap()
19
20
if (context != null) {
21
context["traits"] = analytics?.traits()
22
23
workingEvent?.context = context
24
}
25
return workingEvent
26
}
27
}

Once you're up and running, you can take advantage of Analytics-Kotlin's additional features, like Destination Filters, Functions, and Typewriter support.