Ampli for Java SDK

Example

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

Amplitude Data supports tracking analytics events from JRE programs written in Java (6 and higher).

Quick start

  1. Install the Amplitude SDK

    1implementation 'com.amplitude:java-sdk:[1.8.0,2.0)'
    2implementation 'org.json:json:20201115'
  2. Install the Ampli CLI

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

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

    1import com.amplitude.ampli.*;
    2 
    3Ampli.getInstance().load(new LoadOptions()
    4 .setClient(new LoadClientOptions().setApiKey(AMPLITUDE_API_KEY))
    5);
  5. Identify users and set user properties

    1Ampli.getInstance().identify("user-id",
    2 Identify.builder().userProp("A user property").build()
    3);
  6. Track events with strongly typed methods and classes

    1Ampli.getInstance().songPlayed("user_id",
    2 SongPlayed.builder().songId("song-1").build()
    3);
    4Ampli.getInstance().track("user_id",
    5 SongFavorited.builder().songId("song-2").build()
    6);
  7. Flush events before application exit

    1Ampli.getInstance().flush()
  8. Verify implementation status with CLI

    1ampli status [--update]

Install the Amplitude SDK

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

Inside <dependencies> add:

1<dependency>
2 <groupId>com.amplitude</groupId>
3 <artifactId>java-sdk</artifactId>
4 <version>[1.8.0,2.0)</version>
5</dependency>
6<dependency>
7 <groupId>org.json</groupId>
8 <artifactId>json</artifactId>
9 <version>20201115</version>
10</dependency>

1implementation 'com.amplitude:java-sdk:[1.8.0,2.0)'
2implementation 'org.json:json:20201115'

Install Ampli CLI

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

Load

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

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

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

Arg Description
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.

Identify

Call identify() to set user 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.getInstance().identify("user-id", Identify.builder()
2 .userProp("A user property")
3 .build()
4);

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

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

1Ampli.getInstance().identify(
2 userId,
3 Identify.builder().userProp("A trait associated with this user"),.build(),
4 new EventOptions().setDeviceId(deviceId).setUserId("some-user"),
5);

1ampli.identify(userId, Identify(
2 userProp = "A trait associated with this user",
3 )
4 EventOptions(deviceId = "device-id"),
5)

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.

1Ampli.getInstance().setGroup("user-id", "GroupType", "GroupName");

1ampli.setGroup("user-id", "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.

For example, if Joe is in 'orgId' '10' and '20', then the groupName is '[10, 20]').

Your code might look like this:

1Ampli.getInstance().setGroup("user-id", "orgID", ["10", "20"]);

1ampli.setGroup("user-id", "orgId", ["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.getInstance().track(String userId, Event event, EventOptions options, MiddlewareExtra extra)

1ampli.track(userId: String, event: Event, options: EventOptions, extra: MiddlewareExtra)

The options argument allows you to pass Amplitude fields, like price, quantity and revenue. The extra argument lets you pass data to middleware.

For example, in the following code snippet, 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.

The event has an Amplitude field defined: deviceId. Learn more about Amplitude fields here. The event has one MiddlewareExtra defined: extra. Learn more about Middleware.

1MiddlewareExtra extra = new MiddlewareExtra();
2extra.put("extra-key", "extra-value");
3 
4Ampli.getInstance().songPlayed("user-id",
5 SongPlayed.builder()
6 .songId('songId') // String
7 .songFavorited(true) // Boolean
8 .build(),
9 new EventOptions().setDeviceId(deviceId),
10 extra
11);

1ampli.songPlayed("user-id",
2 SongPlayed(
3 songId = 'songId', // String,
4 songFavorited = true, // Boolean
5 ),
6 options = EventOptions(deviceId = "device-id"),
7 extra = MiddlewareExtra(mapOf("extra-key" to "extra-value")
8));

Ampli also generates a class for each event.

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

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

Send Event objects using the generic track method.

1Ampli.getInstance().track("user-id", SongPlayed.builder()
2 .songId('songId') // String
3 .songFavorited(true) // Boolean
4 .build()
5);

1ampli.track("user-id", SongPlayed(
2 songId = 'songId', // String,
3 songFavorited = true, // Boolean
4));

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.

Ampli CLI

Pull

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

1ampli pull

You will be prompted to log in to your workspace 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

Status

Verify that events are implemented 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.