Ampli for Java SDK
Amplitude Data supports tracking analytics events from JRE programs written in Java (6 and higher).
Quick start
- java
implementation 'com.amplitude:java-sdk:[1.8.0,2.0)' implementation 'org.json:json:20201115' - shell
npm install -g @amplitude/ampli Pull the Ampli Wrapper into your project
shellampli pull [--path ./src/main/java/com/amplitude/ampli]- java
import com.amplitude.ampli.*; Ampli.getInstance().load(new LoadOptions() .setClient(new LoadClientOptions().setApiKey(AMPLITUDE_API_KEY)) ); Identify users and set user properties
javaAmpli.getInstance().identify("user-id", Identify.builder().userProp("A user property").build() );Track events with strongly typed methods and classes
javaAmpli.getInstance().songPlayed("user_id", SongPlayed.builder().songId("song-1").build() ); Ampli.getInstance().track("user_id", SongFavorited.builder().songId("song-2").build() );Flush events before application exit
javaAmpli.getInstance().flush()Verify implementation status with CLI
shellampli status [--update]
Install the Amplitude SDK
If you haven't already, install the core Amplitude SDK dependencies.
Inside <dependencies> add:
<dependency>
<groupId>com.amplitude</groupId>
<artifactId>java-sdk</artifactId>
<version>[1.8.0,2.0)</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20201115</version>
</dependency>
Install Ampli CLI
Install the Ampli CLI from Homebrew or npm.
brew tap amplitude/ampli
brew install 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. Run Ampli CLI commands from the project root directory.
ampli pull
Load
Initialize Ampli in your code. The load() method accepts configuration option arguments:
import com.amplitude.ampli.*;
Ampli.getInstance().load(new LoadOptions()
.setClient(new LoadClientOptions().setApiKey(AMPLITUDE_API_KEY))
);
| 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.
Ampli creates types for user properties, the same way it creates types for events and their 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("user-id", Identify.builder()
.userProp("A user property")
.build()
);
The options argument lets you pass Amplitude fields for this call, such as deviceId.
Ampli.getInstance().identify(
userId,
Identify.builder().userProp("A trait associated with this user").build(),
new EventOptions().setDeviceId(deviceId).setUserId("some-user"),
);
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.
Ampli.getInstance().setGroup("user-id", "GroupType", "GroupName");
Amplitude supports assigning users to groups and running queries on those groups, such as Count by Distinct. If at least one member of the group performs a specific event, the count includes the group.
For example, to group users by organization, use 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 you set 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 is sport with groupName values like tennis and baseball.
Setting a group also sets groupType:groupName as a user property, and overwrites any existing groupName value for that user's groupType and the corresponding user property value. groupType is a string. groupName can be a string or an array of strings, which indicates that a user is in multiple groups.
For example, if Joe is in orgId 10 and 20, the groupName is [10, 20].
Your code might look like this:
Ampli.getInstance().setGroup("user-id", "orgID", ["10", "20"]);
Track
To track an event, call the event's corresponding function. Every event in your tracking plan has its own function in the Ampli Wrapper. The call uses this structure:
Ampli.getInstance().track(String userId, Event event, EventOptions options, MiddlewareExtra extra)
The options argument lets you 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 has two required properties: songId and songFavorited. The property type for songId is string, and songFavorited is a boolean.
The event defines one Amplitude field: deviceId. The event also defines one MiddlewareExtra: extra. For more information, refer to Middleware.
MiddlewareExtra extra = new MiddlewareExtra();
extra.put("extra-key", "extra-value");
Ampli.getInstance().songPlayed("user-id",
SongPlayed.builder()
.songId('songId') // String
.songFavorited(true) // Boolean
.build(),
new EventOptions().setDeviceId(deviceId),
extra
);
Ampli also generates a class for each event.
SongPlayed event = SongPlayed.builder()
.songId('songId') // String
.songFavorited(true) // Boolean
.build()
Send Event objects using the generic track method.
Ampli.getInstance().track("user-id", SongPlayed.builder()
.songId('songId') // String
.songFavorited(true) // Boolean
.build()
);
Flush
The Ampli Wrapper queues events and sends them at an interval based on the configuration.
Call flush() to immediately send any pending events.
The flush() method returns a promise you can use to confirm that Ampli has sent all pending events before continuing. Call flush() before the application exits.
Ampli flushes buffered events automatically when it reaches flushQueueSize or flushInterval.
Ampli sends events automatically without calling flush(). Use flush() when 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.
ampli pull
Ampli prompts you 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
Status
Verify that your code implements all tracking-plan events with the status command:
ampli status [--update]
The output displays the status and shows which 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.
Was this helpful?