JRE Java SDK reference

このページはまだあなたの言語に翻訳されていません。 現在取り組んでいますので、後でもう一度確認してください。

This reference documents every public class of com.amplitude:java-sdk and every configuration setter on the client, verified against version 1.13.1. For configuration, go to Configuration options. To find the release that added or changed a feature, go to the Java SDK changelog.

java
import com.amplitude.Amplitude;
import com.amplitude.Event;

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

All classes are in the com.amplitude package, except the exceptions in com.amplitude.exception. The SDK has no static tracking functions: every call goes through an Amplitude instance from getInstance(). Instances with different names are independent, each with its own API key, configuration, queue, and threads.

Setup

getInstance

Returns the instance registered under a name, and creates it on first use. Calling it again with the same name returns the same object, until you call shutdown() on it.

java
public static Amplitude getInstance()
public static Amplitude getInstance(String instanceName)

init

Sets the API key and resets the upload endpoint to the HTTP V2 API. Call it before any other setter, because it also turns off batch mode.

java
public void init(String key)

init() doesn't check the key. An invalid key shows up only when an upload fails. Go to Read the upload result.

flushEvents

Hands every queued event to the upload thread pool and returns immediately. It doesn't wait for the upload.

java
public void flushEvents()

shutdown

Stops the instance's upload and retry thread pools, and removes the instance from the getInstance() registry. Uploads already handed to the pool finish. Events in the retry buffer get a callback with status 0 and the message Client shutdown. Events not retry.

java
public void shutdown() throws InterruptedException

shutdown() doesn't flush. Call flushEvents() first, or you lose queued events. Go to Flush and shut down. Requires 1.10.0 or later.

java
Amplitude client = Amplitude.getInstance();
client.init("AMPLITUDE_API_KEY");
client.logEvent(new Event("Report Exported", "user-12345"));

client.flushEvents();
client.shutdown();

Tracking

logEvent

Runs the event through middleware and adds it to the upload queue. Before middleware runs, the event receives the instance's Plan and IngestionMetadata if it has none of its own.

java
public void logEvent(Event event)
public void logEvent(Event event, AmplitudeCallbacks callbacks)
public void logEvent(Event event, MiddlewareExtra extra)
public void logEvent(Event event, AmplitudeCallbacks callbacks, MiddlewareExtra extra)

If the queue holds setEventUploadThreshold() events after this call, the SDK starts an upload. Otherwise, it schedules one for setEventUploadPeriodMillis() later.

java
Amplitude client = Amplitude.getInstance();
client.init("AMPLITUDE_API_KEY");

client.logEvent(new Event("Button Clicked", "user-12345"));

addEventMiddleware

Adds a middleware to the end of the chain. Go to Middleware. Requires 1.6.0 or later.

java
public synchronized void addEventMiddleware(Middleware middleware)

shouldWait

Returns true when the instance is busy, so you can slow down before the next logEvent(). Requires 1.6.1 or later.

java
public boolean shouldWait(Event event)

shouldWait() returns true when any of these conditions is true:

  • The queue holds more events than the upload threshold.
  • The retry buffer holds 16,000 events or more.
  • setRecordThrottledId(true) is on, and Amplitude recently throttled the event's userId or deviceId.

Event

An event to send. Every event needs eventType and at least one of userId or deviceId. Every other field is a public field you set directly. The SDK collects no device or location data itself.

java
public Event(String eventType, String userId)
public Event(String eventType, String userId, String deviceId)

Both constructors throw IllegalArgumentException (Event must have one defined userId and/or deviceId) when userId and deviceId are both null.

Property helpers

These methods return the event, so you can chain them. Requires 1.13.0 or later.

java
Amplitude client = Amplitude.getInstance();
client.init("AMPLITUDE_API_KEY");

Event event = new Event("Song Played", "user-12345")
    .addEventProperty("genre", "jazz")
    .addEventProperty("duration_seconds", 214)
    .addUserProperty("plan", "premium");
client.logEvent(event);
json
{
  "event_type": "Song Played",
  "user_id": "user-12345",
  "event_properties": { "genre": "jazz", "duration_seconds": 214 },
  "user_properties": { "plan": "premium" }
}

toJsonObject() returns the event as the SDK uploads it, and toString() returns the same JSON as a string.

Event fields

The SDK also sets library to amplitude-java/<version> on every upload.

Limits

The SDK checks property objects (eventProperties, userProperties, groups, groupProperties) when it builds the upload, including nested objects and arrays:

  • The SDK cuts a string value longer than 1,000 characters to 1,000.
  • An object with more than 1,024 keys throws IllegalArgumentException (Too many properties (more than 1024) in JSON) on the upload thread. The SDK reports the whole batch to callbacks with status 0.

AmplitudeCallbacks

Receives the upload result for each event. Extend the class and override its one method. Requires 1.4.0 or later.

java
public void onLogEventServerResponse(Event event, int status, String message)

The SDK calls onLogEventServerResponse() on an upload or retry thread. Register an instance-wide callback with setCallbacks(), or pass one to logEvent() for a single event. When both exist, both run: the instance callback first.

Middleware

Runs custom code on every event in logEvent(), before the event joins the queue. Requires 1.6.0 or later.

java
public interface Middleware {
  void run(MiddlewarePayload payload, MiddlewareNext next);
}

public interface MiddlewareNext {
  void run(MiddlewarePayload curPayload);
}

Middleware runs in the order you added it, on the thread that called logEvent(). Call next.run(payload) to pass the event on. If a middleware doesn't call next, the SDK drops the event without a callback.

MiddlewarePayload

Constructors: MiddlewarePayload(Event event) and MiddlewarePayload(Event event, MiddlewareExtra extra).

MiddlewareExtra

A HashMap<String, Object> for data you pass from logEvent() to your middleware. Constructors: MiddlewareExtra() and MiddlewareExtra(Map<String, Object> map).

Options

Instructions sent to Amplitude with each upload request. Pass them with setOptions(). Each setter returns the Options object, so you can chain them.

The SDK always sends Content-Type: application/json and Accept: application/json, then applies custom headers. A custom header with the same name replaces the default header. minIdLength and headers are also public fields.

Plan

Tracking plan information. Every setter returns the Plan object. Requires 1.8.0 or later.

The SDK omits empty values.

IngestionMetadata

The source of the events. Every setter returns the IngestionMetadata object. Requires 1.11.0 or later.

java
Amplitude client = Amplitude.getInstance();
client.init("AMPLITUDE_API_KEY");
client.setPlan(new Plan().setBranch("main").setVersion("3"));
client.setIngestionMetadata(new IngestionMetadata()
    .setSourceName("billing-service")
    .setSourceVersion("2.1.0"));

client.logEvent(new Event("Invoice Paid", "user-12345"));
json
{
  "event_type": "Invoice Paid",
  "user_id": "user-12345",
  "plan": { "branch": "main", "version": "3" },
  "ingestion_metadata": {
    "source_name": "billing-service",
    "source_version": "2.1.0"
  }
}

AmplitudeLog

The SDK's logger. It writes ERROR messages to standard error and lower levels to standard output, in the format <tag>: <message>. Extend it to send SDK messages to your logging framework, and register it with setLogger().

LogMode

getLogLevel() requires 1.12.0 or later. The level field is private, so custom loggers compare levels with getLogLevel().

Status

The result categories the SDK assigns to upload responses. Your code doesn't receive a Status directly: callbacks get the HTTP status code.

Exceptions

com.amplitude.exception.AmplitudeException is the abstract base class. AmplitudeInvalidAPIKeyException extends it. The SDK throws AmplitudeInvalidAPIKeyException internally when Amplitude answers Invalid API key, and reports it to callbacks with status 0. No public method throws it.

Constants

The Constants interface holds the SDK's fixed values.

Internal classes

HttpCall, HttpCallMode, Response, MiddlewareRunner, and Utils are public because the SDK uses them across files. Don't use them in your code: they have no supported use and can change in any release.

Configuration options

The SDK has no options object. You configure each instance with setters, after init(). You can chain setters that return Amplitude.

java
Amplitude client = Amplitude.getInstance();
client.init("AMPLITUDE_API_KEY");
client.setEventUploadThreshold(50)
    .setEventUploadPeriodMillis(5000)
    .setFlushTimeout(5000L);
client.setLogMode(AmplitudeLog.LogMode.WARN);

client.logEvent(new Event("Button Clicked", "user-12345"));

Delivery

Data

Instance and logging

これは役に立ちましたか?

For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.

このページでは