Java

The backend Java SDK (separate from Android)

Amplitude and Ampli SDK

Ampli SDK is autogenerated library based on your pre-defined tracking plan. The Ampli SDK, is a lightweight wrapper over the Amplitude SDK that provides type-safety, supports linting, and enables features like input validation. The code replicates the spec in the Tracking Plan and enforces its rules and requirements. This guide is about Amplitude SDK. To learn more about Ampli SDK, please refer to the Ampli JRE and examples.

SDK Installation

1a. Maven

Use Gradle or another build system to resolve the Java SDK dependency. The following example is for Gradle:

dependencies {
    implementation 'org.json:json:20201115'
    implementation 'com.amplitude:java-sdk:1.9.0'
}

1b. Download (alternative)

Download the latest JAR file and add it to the project's buildpath. See instructions for your IDE.

EU Data Residency

Sending data to Amplitude's EU servers, you need to configure the server url during the initialization.

Amplitude amplitude = Amplitude.getInstance();
amplitude.init("API KEY");
amplitude.setServerUrl("https://api.eu.amplitude.com/2/httpapi");

Usage & Examples

Importing

Import Amplitude into any file that uses it. We use the open source JSONObject library to conveniently create JSON key-value objects.

import com.amplitude.Amplitude;
import org.json.JSONObject;

Initialization

Initialization is necessary before any instrumentation is done. The API key for your Amplitude project is required.

Amplitude client = Amplitude.getInstance();
client.init("YOUR_API_KEY");

Amplitude.getInstance(String name) may optionally take a name which uniquely holds settings.

Amplitude client = Amplitude.getInstance("YOUR_INSTANCE_NAME");
client.init("YOUR_API_KEY");

Configure batching behavior

To support high performance environments, our SDK send events in batch. Every event logged by logEvent method is queued in memory. Events are flushed in batch in background. There are two properties we can use to customize batching behavior.

Amplitude client = Amplitude.getInstance();
// events queued in memory will flush when number of events exceed upload threshold
// default value is 10
client.setEventUploadThreshold(20);

// events queue will flush every certain milliseconds based on setting
// default value is 10,000 milliseconds
client.setEventUploadPeriodMillis(5000);

Events can also be flushed on demand.

client.flushEvents();

For customers who want to send large batches of data at a time, for example through scheduled jobs, rather than in a continuous realtime stream, we provide the batch mode. Both the regular mode and the batch mode use the same events upload threshold and flush time intervals, but the batch mode allows larger payload size(20MB) and has higher throttling limit. Due to the higher rate of data that is permitted by this mode, data sent by batch mode may be delayed based on load. You can see a usage example in this project on GitHub.

// Enable batch mode
client.useBatchMode(true);

// Disable batch mode
client.useBatchMode(false);

Config custom http proxy

New in version 1.9.0. Set and unset custom proxy for http requests.

import java.net.Proxy;

// set custom proxy
client.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(“proxyHost”, port)));

// unset proxy
client.setProxy(Proxy.NO_PROXY);

Sending Events

Events represent how users interact with your application. For example, “Button Clicked” may be an action you want to track.

🚧

IMPORTANT NOTE

For testing Java SDK out, please make sure your main thread continues until the background daemon thread that has the Amplitude HTTP request is finished. Otherwise, the main thread terminated earlier than the daemon thread will lead logEvent to fail silently.

Amplitude client = Amplitude.getInstance();
client.logEvent(new Event("Button Clicked", "test_user_id"));

Events with Properties

Events can also contain properties. They provide context about the event taken. For example, “hover time” may be a relevant event property to “button click."

Event event = new Event("Button Clicked", "test_user_id");

JSONObject eventProps = new JSONObject();
try {
  eventProps.put("Hover Time", 10).put("prop_2", "value_2");
} catch (JSONException e) {
  System.err.println("Invalid JSON");
  e.printStackTrace();
}

event.eventProperties = eventProps;

client.logEvent(event);

Set User Properties

🚧

Privacy and Tracking

Please be sure to not track any user data that may be against your privacy terms. If you need any assistance with privacy concerns, then please reach out to our Platform team.

Use event.userProperties as a shorthand to set multiple user properties at once.

Event event = new Event("Button Clicked", "test_user_id");

JSONObject userProps = new JSONObject();
double[] arr = {1,2,4,8};
try {
  userProps.put("team", "red").put("running_times", arr);
} catch (JSONException e) {
  e.printStackTrace();
  System.err.println("Invalid JSON");
}

event.userProperties = userProps;
client.logEvent(event);

Set Device Information

Unlike other SDKs like Android SDK or iOS SDK, device information in Java SDK is not collected via SDK. Device information like device id, device brand, device manufacturer, and device model can be set as properties in event if needed. However, for now that information may be needed to set in every event.

Event event = new Event("Button Clicked", "test_user_id");
event.deviceId = "device_id";
event.deviceBrand = "device_brand";
event.deviceManufacturer = "device_manufacturer";
event.deviceModel = "device_model";
client.logEvent(event);

Set Session Information

Session id can set in event as well, like other properties. This pattern also applies to other properties like city, price, etc. Full list of events properties can be found here.

Event event = new Event("Button Clicked", "test_user_id");
event.sessionId = 1;
client.logEvent(event);

Amplitude Callbacks

From 1.4.0, we add the support for AmplitudeCallbacks. The callbacks now can trigger a callback when event is sent to server or failed after retries.

Amplitude client = Amplitude.getInstance();
AmplitudeCallbacks callbacks =
  new AmplitudeCallbacks() {
  @Override
    public void onLogEventServerResponse(Event event, int status, String message) {
    // Event: Event processed.
    // status: response code, like 200, 400, etc.
    // message: success or error message.
  }
};
client.setCallbacks(callbacks);

From 1.5.0, callbacks can be added to event level and triggered when the event is sent to server or failed after retries. One event can trigger both client level callbacks and event level callbacks.

Amplitude client = Amplitude.getInstance();
AmplitudeCallbacks eventCallbacks =
  new AmplitudeCallbacks() {
  @Override
    public void onLogEventServerResponse(Event event, int status, String message) {
    // Event: Event processed.
    // status: response code, like 200, 400, etc.
    // message: success or error message.
  }
};
client.logEvent(event, eventCallbacks)

Middleware

Middleware allows you to extend Amplitude by running a sequence of custom code on every event. This pattern is flexible and can be used to support event enrichment, transformation, filtering, routing to third-party destinations, and more.

Each Middleware is a simple interface with a run method:

void run(MiddlewarePayload payload, MiddlewareNext next);

The payload contains the event being sent as well as an optional extra that allows you to pass custom data to your own Middleware implementations.

To invoke the next Middleware in the queue, use the next function. You must call next.run(payload) to continue the Middleware chain. If a Middleware doesn't call next, then the event processing stop executing after the current Middleware completes.

Middleware is added to Amplitude via client.addEventMiddleware. You can add as many Middleware as you like. Each Middleware runs in the order in which it was added.

You can find sample example for Java and Kotlin.

Troubleshooting

When debugging, please also check the logs. Amplitude-Java SDK will print out error messages on where we implement it.

Need Help?

Please create new issues directly at the GitHub issues page.


Did this page help you?