Android Ampli Wrapper
Overview¶
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 can benefit your app by providing autocompletion for events & properties defined in Data and enforce your event schemas in code to prevent bad instrumentation.
Amplitude Data supports tracking analytics events from Android apps written in Kotlin and Java.
Ampli Android Resources
Ampli Wrapper versus the Amplitude SDK
We recommend using the Ampli wrapper for all the benefits mentioned above. However, if you want to send events without creating a tracking plan in Amplitude Data, you can learn more about the underlying Amplitude SDK in our SDK Quickstart Guide.
Visit the Amplitude Android SDK documentation.
Quick Start¶
-
(Prerequisite) Create a Tracking Plan in Amplitude Data
Plan your events and properties in Amplitude Data. See detailed instructions here
-
implementation 'com.amplitude:analytics-android:1.+'
-
npm install -g @amplitude/ampli
-
Pull the Ampli Wrapper into your project
ampli pull [--path ./app/src/main/java/com/amplitude/ampli]
-
import com.amplitude.ampli.* ampli.load(appContext, LoadOptions( client = LoadClientOptions(apiKey = AMPLITUDE_API_KEY) ))
-
Identify users and set user properties
ampli.identify(userId, Identify( userProp = "A trait associated with this user" ))
-
Track events with strongly typed methods and classes
ampli.songPlayed(songId = "song-1") ampli.track(SongFavorited(songId = "song-2"))
-
Flush events before application exit
ampli.flush()
-
Verify implementation status with CLI
ampli status [--update]
Installation¶
Install the Amplitude SDK¶
If you haven't already, install the core Amplitude SDK dependencies.
implementation 'com.amplitude:analytics-android:1.+'
implementation '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.
brew tap amplitude/ampli
brew install ampli
npm 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.
ampli pull
API¶
Load¶
Initialize Ampli in your code. The load()
method accepts configuration option arguments:
import com.amplitude.ampli.*;
Ampli.getInstance().load(this, new LoadOptions()
.setClient(new LoadClientOptions().setApiKey(AMPLITUDE_API_KEY))
);
import com.amplitude.ampli.*
ampli.load(appContext, LoadOptions(
client = LoadClientOptions(apiKey = AMPLITUDE_API_KEY)
))
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. |
environment |
Required. String. Specifies the environment the Ampli Wrapper is running in. For example, production or development . Create, rename, and manage environments in Amplitude Data.Environment determines which API token is used when sending events. If a client.apiKey or client.instance is provided, environment is ignored, and can be omitted. |
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 |
Optional. Specifies an Amplitude instance. By default Ampli creates an instance for you. |
client.apiKey |
Optional. 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.
Ampli.getInstance().identify(userId, Identify.builder()
.userProp("A trait associated with this user")
.build()
);
ampli.identify(userId, Identify(
userProp = "A trait associated with this user"
))
The options argument allows you to pass Amplitude fields for this call, such as deviceId
.
EventOptions eventOptions = new EventOptions();
eventOptions.setDeviceId("deviceId");
Ampli.getInstance().identify(
userId,
Identify.builder().userProp("A trait associated with this user").build(),
eventOptions
);
val eventOptions = EventOptions();
eventOptions.deviceId = "device-id";
ampli.identify(
userId,
Identify(
userProp = "A trait associated with this user",
),
eventOptions
)
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.
Ampli.getInstance().groupIdentify("test group", "android-java-ampli", Group.builder()
.requiredBoolean(true)
.build()
);
ampli.groupIdentify("test group", "android-kotlin-ampli", Group(requiredBoolean = true))
Group¶
Feature availability
This feature is available in accounts with a Growth or Enterprise plan with the Accounts add-on.
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.
Ampli.getInstance().getClient().setGroup("groupType", "groupName");
ampli.client?.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:
Ampli.getInstance().getClient().setGroup("orgID", new String[]{"10", "20"});
ampli.client?.setGroup("orgId", arrayOf("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:
Ampli.getInstance().eventName(EventName event, EventOptions options)
ampli.eventName(...eventNameProperties)
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.
Ampli.getInstance().songPlayed(SongPlayed.builder()
.songId("songId") // String
.songFavorited(true) // Boolean
.build()
);
ampli.songPlayed(
songId = "songId", // String,
songFavorited = true, // Boolean
)
Ampli also generates a class for each event.
SongPlayed event = SongPlayed.builder()
.songId("songId") // String
.songFavorited(true) // Boolean
.build()
val myEventObject = SongPlayed(
songId = "songId", // String,
songFavorited = true, // Boolean
);
Send event objects using the generic track method.
EventOptions options = new EventOptions();
options.setUserId("user-id");
Ampli.getInstance().track(SongPlayed.builder()
.songId("songId") // String
.songFavorited(true) // Boolean
.build(), options);
val options = EventOptions()
options.userId = "user_id"
ampli.track(SongPlayed(
songId = "songId", // String
songFavorited = true, // Boolean
), 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.flush()
ampli.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. Destination Plugin example:
public class SegmentDestinationPlugin extends DestinationPlugin {
android.content.Context context;
Analytics analytics;
String SEGMENT_API_KEY;
public SegmentDestinationPlugin(android.content.Context appContext, String segmentAPIKey) {
this.context = appContext;
this.SEGMENT_WRITE_KEY = segmentWriteKey;
}
@Override
public void setup(Amplitude amplitude) {
super.setup(amplitude);
analytics = new Analytics.Builder(this.context, SEGMENT_API_KEY)
.build();
Analytics.setSingletonInstance(analytics);
}
@Override
public BaseEvent track(BaseEvent event) {
Properties properties = new Properties();
for (Map.Entry<String,Object> entry : event.getEventProperties().entrySet()) {
properties.putValue(entry.getKey(),entry.getValue());
}
analytics.track(event.eventType, properties);
return event;
}
}
class SegmentDestinationPlugin(appContext: Context, segmentApiKey: String) : DestinationPlugin() {
var analytics: Analytics? = null;
val context: Context = appContext;
init {
analytics = Analytics.Builder(appContext, segmentApiKey).build()
}
override fun track(event: BaseEvent): BaseEvent {
val eventProperties = Properties();
event.eventProperties?.forEach { entry -> entry.value?.let {
eventProperties.put(entry.key,
it)
} }
analytics?.track(event.eventType, eventProperties);
return event
}
}
Add your plugin after init Ampli.
Ampli.getInstance().getClient().add(
new YourDestinationPlugin(this, DESTINATION_API_KEY)
);
ampli.client?.add(
YourDestinationPlugin(this, DESTINATION_API_KEY)
)
Ampli CLI¶
Pull¶
The pull
command downloads the Ampli Wrapper code to your project. Run the pull
command from the project root.
ampli pull
You will be prompted to log in to your workspace and select a source.
➜ ampli pull
Ampli project is not initialized. No existing `ampli.json` configuration found.
? Create a new Ampli project here? Yes
? Organization: Amplitude
? Workspace: My Workspace
? Source: My Source
Learn more about ampli pull
.
Status¶
Verify that events are implemented in your code with the status command:
ampli status [--update]
The output displays status and indicates what events are missing.
➜ ampli status
✘ Verifying event tracking implementation in source code
✔ Song Played (1 location)
✘ Song Stopped Called when a user stops playing a song.
Events Tracked: 1 missed, 2 total
Learn more about ampli status
.