Ampli for Android-Kotlin SDK

Example

See examples of Ampli implementations for the following languages on GitHub:

The Ampli Wrapper is a generated, strongly typed API for tracking Analytics events based on your Tracking Plan in Amplitude Data. The tracking library exposes a function for every event in your team’s tracking plan. The function’s arguments correspond to the event’s properties.

Ampli provides autocompletion for events & properties defined in Data and enforce your event schemas in code to prevent bad instrumentation.

Quick start

  1. (Prerequisite) Create a Tracking Plan in Amplitude Data

    Plan your events and properties in Amplitude Data.

  2. Install the Amplitude SDK

    1implementation 'com.amplitude:analytics-android:1.+'
  3. Install the Ampli CLI

    1npm install -g @amplitude/ampli
  4. Pull the Ampli Wrapper into your project

    1ampli pull [--path ./app/src/main/java/com/amplitude/ampli]
  5. Initialize the Ampli Wrapper

    1import com.amplitude.ampli.*
    2 
    3ampli.load(appContext, LoadOptions(
    4 client = LoadClientOptions(apiKey = AMPLITUDE_API_KEY)
    5))
  6. Identify users and set user properties

    1ampli.identify(userId, Identify(
    2 userProp = "A trait associated with this user"
    3))
  7. Track events with strongly typed methods and classes

    1ampli.songPlayed(songId = "song-1")
    2ampli.track(SongFavorited(songId = "song-2"))
  8. Flush events before application exit

    1ampli.flush();
  9. Verify implementation status with CLI

    1ampli status [--update]

Install the Amplitude SDK

If you haven't already, install the core Amplitude SDK dependencies.

1implementation 'com.amplitude:analytics-android:1.+'

Note

If you're not already requesting the INTERNET permission, add <uses-permission android:name="android.permission.INTERNET" /> to your AndroidManifest.xml.

Install the Ampli CLI

You can install the Ampli CLI from Homebrew or npm.

1brew tap amplitude/ampli
2brew install ampli

1npm install -g @amplitude/ampli

Pull the Ampli Wrapper into your project

Run the Ampli CLI pull command to log in to Amplitude Data and download the strongly typed Ampli Wrapper for your tracking plan. Ampli CLI commands are usually run from the project root directory.

1ampli pull

API

Ampli generates a thin facade over the Amplitude SDK which provides convenience methods. The Ampli Wrapper also grants access to every method of the underlying Amplitude SDK through ampli.client. More details.

Load

Initialize Ampli in your code. The load() method accepts configuration option arguments:

1import com.amplitude.ampli.*
2 
3ampli.load(appContext, LoadOptions(
4 client = LoadClientOptions(apiKey = AMPLITUDE_API_KEY)
5))

1import com.amplitude.ampli.*;
2 
3Ampli.getInstance().load(this, new LoadOptions()
4 .setClient(new LoadClientOptions().setApiKey(AMPLITUDE_API_KEY))
5);

Arg Description
appContext An object with a set of properties to add to every event sent by the Ampli Wrapper. This option is available when there is at least one source template associated with your team's tracking plan.
LoadOptions Required. Specifies configuration options for the Ampli Wrapper.
disabled Optional. Specifies whether the Ampli Wrapper does any work. When true, all calls to the Ampli Wrapper are no-ops. Useful in local or development environments.
client.instance Required if client.apiKey isn't set. Specifies an Amplitude instance. By default Ampli creates an instance for you.
client.apiKey Required if client.instance isn't set. Specifies an API Key. This option overrides the default, which is the API Key configured in your tracking plan.
client.configuration Optional. Specifies the Amplitude configuration. This option overrides the default configuration.

Identify

Call identify() to identify a user in your app and associate all future events with their identity, or to set their properties.

Just as Ampli creates types for events and their properties, it creates types for user properties.

The identify() function accepts an optional userId, optional user properties, and optional options.

For example your tracking plan contains a user property called userProp. The property's type is a string.

1ampli.identify(userId, Identify(
2 userProp = "A trait associated with this user"
3))

1Ampli.getInstance().identify(userId, Identify.builder()
2 .userProp("A trait associated with this user")
3 .build()
4);

The options argument allows you to pass Amplitude fields for this call, such as deviceId.

1val eventOptions = EventOptions();
2eventOptions.deviceId = "device-id";
3 
4ampli.identify(
5 userId,
6 Identify(
7 userProp = "A trait associated with this user",
8 ),
9 eventOptions
10)

1EventOptions eventOptions = new EventOptions();
2eventOptions.setDeviceId("deviceId");
3 
4Ampli.getInstance().identify(
5 userId,
6 Identify.builder().userProp("A trait associated with this user").build(),
7 eventOptions
8);

Group identify

Call groupIdentify() to identify a group in your app and set/update group properties.

Just as Ampli creates types for events and their properties, it creates types for group properties.

The groupIdentify() function accepts a string group_type, a string group_name, an Group event instance, and an optional EventOptions.

For example your tracking plan contains a group test group:android-java-ampli has a property called requiredBoolean with a boolean type.

1ampli.groupIdentify("test group", "android-kotlin-ampli", Group(requiredBoolean = true))

1Ampli.getInstance().groupIdentify("test group", "android-java-ampli", Group.builder()
2 .requiredBoolean(true)
3 .build()
4);

Group

Call setGroup() to associate a user with their group (for example, their department or company). The setGroup() function accepts a required groupType, and groupName and an optional EventOptions.

1ampli.client?.setGroup("groupType", "groupName")

1Ampli.getInstance().getClient().setGroup("groupType", "groupName");

Amplitude supports assigning users to groups and performing queries, such as Count by Distinct, on those groups. If at least one member of the group has performed the specific event, then the count includes the group.

For example, you want to group your users based on what organization they're in by using an 'orgId'. Joe is in 'orgId' '10', and Sue is in 'orgId' '15'. Sue and Joe both perform a certain event. You can query their organizations in the Event Segmentation Chart.

When setting groups, define a groupType and groupName. In the previous example, 'orgId' is the groupType and '10' and '15' are the values for groupName. Another example of a groupType could be 'sport' with groupName values like 'tennis' and 'baseball'.

Setting a group also sets the groupType:groupName as a user property, and overwrites any existing groupName value set for that user's groupType, and the corresponding user property value. groupType is a string, and groupName can be either a string or an array of strings to indicate that a user is in multiple groups.

GroupType is a string, and groupName can be either a string or an array of strings to show that a user is in multiple groups. For example, if Joe is in 'orgId' '10' and '20', then the groupName is '[10, 20]'.

Your code might look like this:

1ampli.client?.setGroup("orgId", arrayOf("10", "20"))

1Ampli.getInstance().getClient().setGroup("orgID", new String[]{"10", "20"});

Track

To track an event, call the event's corresponding function. Every event in your tracking plan gets its own function in the Ampli Wrapper. The call is structured like this:

1ampli.eventName(...eventNameProperties)

1Ampli.getInstance().eventName(EventName event, EventOptions options)

The options argument allows you to pass Amplitude fields, like deviceID.

For example, in the following code snippets, your tracking plan contains an event called songPlayed. The event is defined with two required properties: songId and songFavorited. The property type for songId is string, and songFavorited is a boolean.

1ampli.songPlayed(
2 songId = "songId", // String,
3 songFavorited = true, // Boolean
4)

1Ampli.getInstance().songPlayed(SongPlayed.builder()
2 .songId("songId") // String
3 .songFavorited(true) // Boolean
4 .build()
5);

Ampli also generates a class for each event.

1val myEventObject = SongPlayed(
2 songId = "songId", // String,
3 songFavorited = true, // Boolean
4);

1SongPlayed event = SongPlayed.builder()
2 .songId("songId") // String
3 .songFavorited(true) // Boolean
4 .build()

Send event objects using the generic track method.

1val options = EventOptions()
2options.userId = "user_id"
3 
4ampli.track(SongPlayed(
5 songId = "songId", // String
6 songFavorited = true, // Boolean
7 ), options);

1EventOptions options = new EventOptions();
2options.setUserId("user-id");
3 
4Ampli.getInstance().track(SongPlayed.builder()
5 .songId("songId") // String
6 .songFavorited(true) // Boolean
7 .build(), options);

Flush

The Ampli wrapper queues events and sends them on an interval based on the configuration.

Call flush() to immediately send any pending events.

The flush() method returns a promise that can be used to ensure all pending events have been sent before continuing.
This can be useful to call prior to application exit.

Ampli flushes events in the buffer automatically when flushQueueSize or flushInterval are reached.

Ampli sends events automatically without calling flush(), but using flush() is useful if you need to send events before the application exits.

1ampli.flush()

Plugin

Plugins allow you to extend the Amplitude behavior, for example, modifying event properties (enrichment type) or sending to third-party APIs (destination type).

First you need to define your plugin. See the following code for a Destination Plugin example.

1class SegmentDestinationPlugin(appContext: Context, segmentApiKey: String) : DestinationPlugin() {
2 var analytics: Analytics? = null;
3 val context: Context = appContext;
4 init {
5 analytics = Analytics.Builder(appContext, segmentApiKey).build()
6 }
7 
8 override fun track(event: BaseEvent): BaseEvent {
9 val eventProperties = Properties();
10 event.eventProperties?.forEach { entry -> entry.value?.let {
11 eventProperties.put(entry.key,
12 it)
13 } }
14 
15 analytics?.track(event.eventType, eventProperties);
16 return event
17 }
18}

1public class SegmentDestinationPlugin extends DestinationPlugin {
2 android.content.Context context;
3 Analytics analytics;
4 String SEGMENT_API_KEY;
5 public SegmentDestinationPlugin(android.content.Context appContext, String segmentAPIKey) {
6 this.context = appContext;
7 this.SEGMENT_WRITE_KEY = segmentWriteKey;
8 }
9 @Override
10 public void setup(Amplitude amplitude) {
11 super.setup(amplitude);
12 analytics = new Analytics.Builder(this.context, SEGMENT_API_KEY)
13 .build();
14 
15 Analytics.setSingletonInstance(analytics);
16 }
17 
18 @Override
19 public BaseEvent track(BaseEvent event) {
20 Properties properties = new Properties();
21 for (Map.Entry<String,Object> entry : event.getEventProperties().entrySet()) {
22 properties.putValue(entry.getKey(),entry.getValue());
23 }
24 analytics.track(event.eventType, properties);
25 return event;
26 }
27}

Add your plugin after init Ampli.

1ampli.client?.add(
2 YourDestinationPlugin(this, DESTINATION_API_KEY)
3 )

1Ampli.getInstance().getClient().add(
2new YourDestinationPlugin(this, DESTINATION_API_KEY)
3);

Ampli CLI

Pull

The pull command downloads the Ampli Wrapper code to your project. Run the pull command from the project root.

1ampli pull

Log in to your workspace when prompted and select a source.

1ampli pull
2Ampli project is not initialized. No existing `ampli.json` configuration found.
3? Create a new Ampli project here? Yes
4? Organization: Amplitude
5? Workspace: My Workspace
6? Source: My Source

Learn more about ampli pull.

Status

Verify that events are in your code with the status command:

1ampli status [--update]

The output displays status and indicates what events are missing.

1ampli status
2Verifying event tracking implementation in source code
3Song Played (1 location)
4Song Stopped Called when a user stops playing a song.
5Events Tracked: 1 missed, 2 total

Learn more about ampli status.

Was this page helpful?

Thanks for your feedback!

July 16th, 2024

Need help? Contact Support

Visit Amplitude.com

Have a look at the Amplitude Blog

Learn more at Amplitude Academy

© 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.