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.
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.
public static Amplitude getInstance()
public static Amplitude getInstance(String instanceName)
| Parameter | Type | Description |
|---|---|---|
instanceName | String | Optional. The instance's name. getInstance() uses the empty string. |
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.
public void init(String key)
| Parameter | Type | Description |
|---|---|---|
key | String | Your Amplitude project's API 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.
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.
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.
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.
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)
| Parameter | Type | Description |
|---|---|---|
event | Event | The event to send. |
callbacks | AmplitudeCallbacks | Optional. Runs for this event, in addition to the instance callback. Requires 1.5.0 or later. |
extra | MiddlewareExtra | Optional. Data for your middleware. The SDK doesn't send it to Amplitude. Requires 1.6.0 or later. |
If the queue holds setEventUploadThreshold() events after this call, the SDK starts an upload. Otherwise, it schedules one for setEventUploadPeriodMillis() later.
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.
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.
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'suserIdordeviceId.
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.
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.
| Method | Description |
|---|---|
setEventProperties(Map<String, Object> properties) | Replaces eventProperties. null clears it. |
addEventProperty(String key, Object value) | Adds or replaces one event property. |
setUserProperties(Map<String, Object> properties) | Replaces userProperties. null clears it. |
addUserProperty(String key, Object value) | Adds or replaces one user property. |
setGroups(Map<String, Object> groups) | Replaces groups. null clears it. |
addGroup(String key, Object value) | Adds or replaces one group. |
setGroupProperties(Map<String, Object> properties) | Replaces groupProperties. null clears it. |
addGroupProperty(String key, Object value) | Adds or replaces one group property. |
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);
{
"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
| Field | Type | Default | Uploaded as | Description |
|---|---|---|---|---|
eventType | String | Constructor argument | event_type | The event name. |
userId | String | Constructor argument | user_id | Your ID for the user. |
deviceId | String | Constructor argument or null | device_id | An ID for the device. |
timestamp | long | Time of construction | time | Milliseconds since the Unix epoch. |
sessionId | long | -1 | session_id | The session's start time in milliseconds. -1 means no session. |
insertId | String | A random UUID | insert_id | Amplitude drops a later event with an insert_id it saw for the same project in the past 7 days. |
eventId | int | 0 | event_id | A counter you can use to order events with the same timestamp. |
eventProperties | JSONObject | null | event_properties | Properties of the event. |
userProperties | JSONObject | null | user_properties | Properties to set on the user. |
groups | JSONObject | null | groups | Group type to group name or names. Requires the Accounts add-on. |
groupProperties | JSONObject | null | group_properties | Properties to set on the groups in groups, for a $groupidentify event. |
appVersion | String | null | app_version | Your application's version. Omitted from the upload when null. |
versionName | String | null | version_name | Legacy version name. |
platform | String | null | platform | The platform, such as Server. |
osName | String | null | os_name | Operating system or browser name. |
osVersion | String | null | os_version | Operating system or browser version. |
deviceBrand | String | null | device_brand | Device brand. |
deviceManufacturer | String | null | device_manufacturer | Device manufacturer. |
deviceModel | String | null | device_model | Device model. |
carrier | String | null | carrier | Mobile carrier. |
country | String | null | country | Country. |
region | String | null | region | Region or state. |
city | String | null | city | City. |
dma | String | null | dma | Designated market area. |
locationLat | double | 0 | location_lat | Latitude. Always uploaded. |
locationLng | double | 0 | location_lng | Longitude. Always uploaded. |
language | String | null | language | The user's language. |
ip | String | null | ip | The user's IP address. $remote uses the IP address of the upload request, which is your server's. |
idfa | String | null | idfa | iOS advertising identifier. |
idfv | String | null | idfv | iOS identifier for vendor. |
adid | String | null | adid | Google Play Services advertising ID. |
androidId | String | null | android_id | Android ID. |
partnerId | String | null | partner_id | Partner ID. Requires 1.8.1 or later. |
price | Double | null | price | Price of the item. Setting price or revenue uploads all six revenue fields. |
quantity | int | 0 | quantity | Quantity of the item. Uploaded as 1 when it's 0 or less. |
revenue | Double | null | revenue | Revenue. When price is also set, Amplitude uses price × quantity. |
productId | String | null | productId | Product identifier. |
revenueType | String | null | revenueType | Revenue type, such as purchase or refund. |
currency | String | null | currency | Three-letter currency code. Requires 1.12.5 or later. |
plan | Plan | The instance's plan | plan | Tracking plan information. Requires 1.8.0 or later. |
ingestionMetadata | IngestionMetadata | The instance's metadata | ingestion_metadata | Source name and version. Requires 1.11.0 or later. |
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 status0.
AmplitudeCallbacks
Receives the upload result for each event. Extend the class and override its one method. Requires 1.4.0 or later.
public void onLogEventServerResponse(Event event, int status, String message)
| Parameter | Type | Description |
|---|---|---|
event | Event | The event. |
status | int | The HTTP status, or 0 when the SDK failed before it got a response. |
message | String | The result. Go to Read the upload result. |
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.
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
| Field | Type | Description |
|---|---|---|
event | Event | The event. Change its fields, or replace it. |
extra | MiddlewareExtra | The extra argument of logEvent(), or null. |
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.
| Method | Default | Description |
|---|---|---|
setMinIdLength(Integer minIdLength) | Not set | The shortest user_id or device_id Amplitude accepts, sent as options.min_id_length. Amplitude's default is 5. |
setHeaders(Map<String, String> headers) | Not set | Replaces the custom HTTP headers for each upload request. Requires 1.7.0 or later. |
addHeader(String key, String value) | Not set | Adds one custom HTTP header. Requires 1.7.0 or later. |
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.
| Method | Uploaded as | Example |
|---|---|---|
setBranch(String branch) | plan.branch | main |
setSource(String source) | plan.source | jre-java |
setVersion(String version) | plan.version | 1 |
setVersionId(String id) | plan.versionId | 9ec23ba0-275f-468f-80d1-66b88bff9529 |
The SDK omits empty values.
IngestionMetadata
The source of the events. Every setter returns the IngestionMetadata object. Requires 1.11.0 or later.
| Method | Uploaded as |
|---|---|
setSourceName(String sourceName) | ingestion_metadata.source_name |
setSourceVersion(String sourceVersion) | ingestion_metadata.source_version |
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"));
{
"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().
| Method | Description |
|---|---|
log(String tag, String message, LogMode messageMode) | Writes a message if messageMode is at or above the logger's level. Override it. |
debug(String tag, String message) | Calls log with DEBUG. |
warn(String tag, String message) | Calls log with WARN. |
error(String tag, String message) | Calls log with ERROR. |
setLogMode(LogMode logMode) | Sets the logger's level. |
getLogMode() | Returns the logger's level. Requires 1.12.0 or later. |
LogMode
| Value | getLogLevel() | Description |
|---|---|---|
DEBUG | 1 | Every message. |
WARN | 2 | Warnings and errors. |
ERROR | 3 | Errors only. The default. |
OFF | 4 | Nothing. |
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.
| Value | HTTP status | What the SDK does |
|---|---|---|
SUCCESS | 200–299 | Reports success. |
INVALID | Other 4xx | Drops the events Amplitude names as invalid, and retries the rest. |
PAYLOAD_TOO_LARGE | 413 | Retries with half the batch, and reports the other half as dropped. |
RATELIMIT | 429 | Drops events for users or devices over their daily quota, and retries the rest. |
TIMEOUT | 408, network error | Retries. |
FAILED | 500 and higher | Retries. |
UNKNOWN | Below 200, 3xx | Reports the result without retrying. |
SKIPPED | None | Defined, but the SDK never assigns it. |
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.
| Constant | Value | Description |
|---|---|---|
API_URL | https://api2.amplitude.com/2/httpapi | Default upload URL. |
BATCH_API_URL | https://api2.amplitude.com/batch | Upload URL in batch mode. |
SDK_LIBRARY | amplitude-java | The library value's prefix. |
SDK_VERSION | 1.13.1 | The SDK version. |
NETWORK_TIMEOUT_MILLIS | 10000 | Connect and read timeout for each request. |
EVENT_BUF_COUNT | 10 | Default upload threshold. |
EVENT_BUF_TIME_MILLIS | 10000 | Default upload period. |
RETRY_TIMEOUTS | 100, 100, 200, 200, 400, 400, 800, 800, 1600, 1600, 3200, 3200 | Waits in milliseconds before each of the 12 retries. |
MAX_CACHED_EVENTS | 16000 | Retry buffer size. |
MAX_PROPERTY_KEYS | 1024 | Maximum number of keys in one property object. |
MAX_STRING_LENGTH | 1000 | Maximum length of a property string value. |
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.
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
| Setter | Type | Default | Description |
|---|---|---|---|
setEventUploadThreshold(int) | int | 10 | Starts an upload when the queue holds this many events. Returns Amplitude. |
setEventUploadPeriodMillis(int) | int | 10000 | Milliseconds between the first event in an empty queue and the scheduled upload. Returns Amplitude. |
setServerUrl(String) | String | https://api2.amplitude.com/2/httpapi | The upload URL. It must start with https://. The SDK opens every request as HTTPS, so an http:// URL fails each upload with a ClassCastException. The SDK ignores a value that starts with neither http:// nor https://. When set, the server URL replaces the batch mode URL. |
useBatchMode(Boolean) | Boolean | false | Sends to the Batch Event Upload API (https://api2.amplitude.com/batch) instead of HTTP V2. init() resets it to false, so call it after init(). |
setOptions(Options) | Options | Not set | Request options and custom headers. |
setProxy(Proxy) | java.net.Proxy | Proxy.NO_PROXY | The proxy for upload requests. Returns Amplitude. Requires 1.9.0 or later. |
setCallbacks(AmplitudeCallbacks) | AmplitudeCallbacks | Not set | The instance-wide upload callback. null removes it. |
setFlushTimeout(long) | long | 0 | Milliseconds an upload task waits for its request. On timeout, it reports the events to callbacks with status 0 and doesn't retry them. 0 waits as long as the request takes, up to the 10-second connect and read timeouts. Returns Amplitude. Requires 1.10.0 or later. |
setRecordThrottledId(boolean) | boolean | false | Remembers users and devices that Amplitude throttled, so shouldWait() can report them. Requires 1.6.1 or later. |
setSendThreadPool(ExecutorService) | ExecutorService | A fixed pool of 20 threads | The pool that runs upload tasks. Returns Amplitude. Requires 1.12.4 or later. |
setRetryThreadPool(ExecutorService) | ExecutorService | A fixed pool of 10 threads | The pool that runs retries. Returns Amplitude. Requires 1.12.4 or later. |
Data
| Setter | Type | Default | Description |
|---|---|---|---|
setPlan(Plan) | Plan | Not set | Added to every event that has no plan of its own. Returns Amplitude. Requires 1.8.0 or later. |
setIngestionMetadata(IngestionMetadata) | IngestionMetadata | Not set | Added to every event that has no metadata of its own. Returns Amplitude. Requires 1.11.0 or later. |
Instance and logging
| Setter | Type | Default | Description |
|---|---|---|---|
setLogMode(LogMode) | LogMode | LogMode.ERROR | The lowest level the current logger writes. Go to Turn on debug logging. |
setLogger(AmplitudeLog) | AmplitudeLog | The built-in logger | A custom logger. Call setLogMode() after setLogger(), because the new logger has its own level. Returns Amplitude. Requires 1.10.0 or later. |
이 내용이 도움이 되었나요?
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.