The Kotlin Android SDK lets you send events to Amplitude.
The Android Kotlin SDK supports Android API level 21 (Android 5.0 Lollipop) and higher.
Amplitude recommends using Android Studio as an IDE and Gradle to manage dependencies.
build.gradle, and sync your project with the updated file.
dependencies {
implementation 'com.amplitude:analytics-android:1.+'
}
pom.xml.
<dependency>
<groupId>com.amplitude</groupId>
<artifactId>analytics-android</artifactId>
<version>[1.0,2.0]</version>
</dependency>
Configuration options
Name
Description
Default Value
deviceIdString?. The device ID to use for this device. If no deviceID is provided one will be generated automatically. Learn more here.null
flushIntervalMillisInt. The amount of time SDK will attempt to upload the unsent events to the server or reach flushQueueSize threshold. The value is in milliseconds.30000
flushQueueSizeInt. SDK will attempt to upload once unsent event count exceeds the event upload threshold or reach flushIntervalMillis interval.30
flushMaxRetriesInt. Maximum retry times.5
minIdLengthInt. The minimum length for user id or device id.5
partnerIdInt. The partner id for partner integration.null
identifyBatchIntervalMillisLong. The amount of time SDK will attempt to batch intercepted identify events. The value is in milliseconds30000
flushEventsOnCloseBoolean. Flushing of unsent events on app close.true
callbackEventCallBack. Callback function after event sent.null
optOutBoolean. Opt the user out of tracking.false
(Deprecated. Use trackingSessionEventsautocapture instead.)Boolean. Automatic tracking of "Start Session" and "End Session" events that count toward event volume.false
(Deprecated. Use defaultTrackingautocapture instead.)DefaultTrackingOptions. Enable tracking of default events for sessions, app lifecycles, screen views, and deep links.DefaultTrackingOptions(sessions = true)
autocaptureSet<AutocaptureOption>. A Set of Options to enable tracking of default events for sessions, application lifecycles, screen and fragment views, deep links, and element interactions.If the parameter isn't set,
AutocaptureOption.SESSIONS is added to the Set by default. For more information, see Autocapture.
interactionsOptionsInteractionsOptions. Configuration for granular control over frustration interaction tracking types (rage clicks and dead clicks).InteractionsOptions(rageClick = RageClickOptions(enabled = true), deadClick = DeadClickOptions(enabled = true))
minTimeBetweenSessionsMillisLong. The amount of time for session timeout. The value is in milliseconds.300000
serverUrlString. The server url events upload to.https://api2.amplitude.com/2/httpapi
serverZoneServerZone.US or ServerZone.EU. The server zone to send to, will adjust server url based on this config.ServerZone.US
useBatchBoolean Whether to use batch API.false
useAdvertisingIdForDeviceIdBoolean. Whether to use advertising id as device id. For more information, see Advertiser ID for required module and permission.false
useAppSetIdForDeviceIdBoolean. Whether to use app set id as device id. For more information, see Application ID for required module and permission.false
trackingOptionsTrackingOptions. Options to control the values tracked in SDK.enable
enableCoppaControlBoolean. Whether to enable COPPA control for tracking options.false
instanceNameString. The name of the instance. Instances with the same name will share storage and identity. For isolated storage and identity use a unique instanceName for each instance.$default_instance
migrateLegacyDataBoolean. Available in 1.9.0+. Whether to migrate maintenance Android SDK data (events, user/device ID). Learn more here.true
offlineBoolean | AndroidNetworkConnectivityCheckerPlugin.Disabled. Whether the SDK is connected to network. Learn more herefalse
storageProviderStorageProvider. Implements StorageProvider interface to store events.AndroidStorageProvider
identifyInterceptStorageProviderStorageProvider. Implements StorageProvider interface for identify event interception and volume optimization.AndroidStorageProvider
identityStorageProviderIdentityStorageProvider. Implements IdentityStorageProvider to store user id and device id.FileIdentityStorageProvider
loggerProviderLoggerProvider. Implements LoggerProvider interface to emit log messages to desired destination.AndroidLoggerProvider
newDeviceIdPerInstallWhether to generate different a device id every time when the app is installed regardless of devices. It's legacy configuration only to keep compatible with the old Android SDK. It works the same as
useAdvertisingIdForDeviceId.false
locationListeningWhether to enable Android location service. Learn more here.
true
To support high-performance environments, the SDK sends events in batches. Every event logged by the track method is queued in memory. Events are flushed in batches in background. You can customize batch behavior with flushQueueSize and flushIntervalMillis. By default, the serverUrl is https://api2.amplitude.com/2/httpapi. For customers who want to send large batches of data at a time, set useBatch to true to set setServerUrl to batch event upload API https://api2.amplitude.com/batch. Both the regular mode and the batch mode use the same events upload threshold and flush time intervals.
import com.amplitude.android.Amplitude
val amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
flushIntervalMillis = 50000,
flushQueueSize = 20,
)
)
import com.amplitude.android.Amplitude;
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.setFlushIntervalMillis(1000);
configuration.setFlushQueueSize(10);
Amplitude amplitude = new Amplitude(configuration);
You can dynamically set the configuration after initialization.
import com.amplitude.android.Amplitude
val amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
)
)
amplitude.configuration.optOut = true
import com.amplitude.android.Amplitude;
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
Amplitude amplitude = new Amplitude(configuration);
amplitude.getConfiguration().setOptOut(true);
You can configure the server zone when initializing the client for sending data to Amplitude's EU servers. The SDK sends data based on the server zone if it's set.
import com.amplitude.android.Amplitude
val amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
serverZone = ServerZone.EU
)
)
import com.amplitude.android.Amplitude;
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.setServerZone(ServerZone.EU);
Amplitude amplitude = new Amplitude(configuration);
Events represent how users interact with your application. For example, "Song Played" may be an action you want to note.
amplitude.track("Song Played")
You can also optionally include event properties.
amplitude.track(
"Song Played",
mutableMapOf<String, Any?>("title" to "Happy Birthday")
)
For more complex events you can create and track a BaseEvent object.
var event = BaseEvent()
event.eventType = "Song Played"
event.eventProperties = mutableMapOf<String, Any?>("title" to "Happy Birthday")
event.groups = mutableMapOf<String, Any?>("test-group-type" to "test-group-value")
event.insertId = 1234
amplitude.track(event)
identify events that contain only set operiatons. This results in fewer sent events and doesn't impact the running of the set operations. Use the identifyBatchIntervalMillis configuration setting to manage the interval at which the SDK flushes batched identify intercepts.Identify is for setting the user properties of a particular user without sending any event. The SDK supports the operations set, setOnce, unset, add, append, prepend, preInsert, postInsert, and remove on individual user properties. Declare the operations via a provided Identify interface. You can chain together multiple operations in a single Identify object. The Identify object is then passed to the Amplitude client to send to the server.
You can handle the identity of a user using the identify methods. Proper use of these methods can connect events to the correct user as they move across devices, browsers, and other platforms. Send an identify call containing those user property operations to Amplitude server to tie a user's events with specific user properties.
val identify = Identify()
identify.set("color", "green")
amplitude.identify(identify)
Starting from release v1.18.0, the SDK can track more events without manual instrumentation. You can configure it to track the following events automatically:
Autocapture options
Name
Type
Enabled by default
Description
SESSIONSAutocaptureOptionYes
Enables session tracking. If the option is set, Amplitude tracks session start and session end events otherwise, Amplitude doesn't track session events. When this setting isn't set, Amplitude tracks
sessionId only. See Track sessions for more information.
APP_LIFECYCLESAutocaptureOptionNo
Enables application lifecycle events tracking. If the option is set, Amplitude tracks application installed, application updated, application opened, and application backgrounded events. Event properties tracked includes:
[Amplitude] Version, [Amplitude] Build, [Amplitude] Previous Version, [Amplitude] Previous Build, [Amplitude] From Background. See Track application lifecycles for more information.
SCREEN_VIEWSAutocaptureOptionNo
Enables screen and fragment views tracking. If the option is set, Amplitude tracks screen viewed and fragment viewed events. Event properties tracked includes:
[Amplitude] Screen Name, [Amplitude] Fragment Class, [Amplitude] Fragment Identifier, [Amplitude] Fragment Tag. See Track screen views for more information.
DEEP_LINKSAutocaptureOptionNo
Enables deep link tracking. If the option is set, Amplitude tracks deep link opened events. Event properties tracked includes:
[Amplitude] Link URL, [Amplitude] Link Referrer. See Track deep links for more information.
ELEMENT_INTERACTIONSAutocaptureOptionNo
Enables element interaction tracking. If the option is set, Amplitude tracks user interactions with clickable elements. Event properties tracked includes:
[Amplitude] Action, [Amplitude] Target Class, [Amplitude] Target Resource, [Amplitude] Target Tag, [Amplitude] Target Source, [Amplitude] Hierarchy, [Amplitude] Screen Name. See Track element interactions for more information.
FRUSTRATION_INTERACTIONSAutocaptureOptionNo
Enables frustration interaction tracking. If the option is enabled, Amplitude tracks frustration interactions (Rage Clicks and Dead Clicks) with clickable UI elements. Rage Clicks generate the
[Amplitude] Rage Click event and Dead Clicks generate the [Amplitude] Dead Click event. Review Track frustration interactions for more information.
You can configure Amplitude to start tracking Autocapture events. Otherwise, you can omit the configuration to keep only session tracking enabled.
autocapture configuration accepts a Set of AutocaptureOption values. To create the Autocapture options, use the autocaptureOptions helper function and add the options to the set with a unary plus sign (+) before each option.
import com.amplitude.android.Amplitude
val amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
autocapture = autocaptureOptions {
+sessions // or `+AutocaptureOption.SESSIONS`
+appLifecycles // or `+AutocaptureOption.APP_LIFECYCLES`
+deepLinks // or `+AutocaptureOption.DEEP_LINKS`
+screenViews // or `+AutocaptureOption.SCREEN_VIEWS`
+elementInteractions // or `+AutocaptureOption.ELEMENT_INTERACTIONS`
+frustrationInteractions // or `+AutocaptureOption.FRUSTRATION_INTERACTIONS`
}
)
)
To enable all autocapture options, use AutocaptureOption.ALL or the addAll() method:
import com.amplitude.android.Amplitude
import com.amplitude.android.AutocaptureOption
// Using AutocaptureOption.ALL constant
val amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
autocapture = AutocaptureOption.ALL
)
)
// Or using addAll() method with builder
val amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
autocapture = autocaptureOptions {
addAll()
}
)
)
By default, if the autocapture configuration isn't explicitly set during Configuration initialization, configuration.autocapture automatically includes AutocaptureOption.SESSIONS.
If you want to prevent automatic session events capture, set autocapture without the AutocaptureOption.SESSIONS option.
import com.amplitude.android.Amplitude
val amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
autocapture = setOf(AutocaptureOption.APP_LIFECYCLES) // or use `setOf()` to disable autocapture.
)
)
autocapture configuration accepts a Set of AutocaptureOption values.
import com.amplitude.android.Amplitude;
import java.util.Arrays;
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.getAutocapture().addAll(Arrays.asList(
AutocaptureOption.SESSIONS,
AutocaptureOption.APP_LIFECYCLES,
AutocaptureOption.DEEP_LINKS,
AutocaptureOption.SCREEN_VIEWS,
AutocaptureOption.ELEMENT_INTERACTIONS,
AutocaptureOption.FRUSTRATION_INTERACTIONS
));
Amplitude amplitude = new Amplitude(configuration);
To enable all autocapture options, use AutocaptureOption.ALL:
import com.amplitude.android.Amplitude;
import com.amplitude.android.AutocaptureOption;
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.getAutocapture().addAll(AutocaptureOption.ALL);
Amplitude amplitude = new Amplitude(configuration);
By default, if the autocapture configuration isn't explicitly set during Configuration initialization, configuration.getAutocapture() automatically includes AutocaptureOption.SESSIONS.
To prevent automatic session event capture, remove the AutocaptureOption.SESSIONS option from autocapture.
import com.amplitude.android.Amplitude;
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.getAutocapture().remove(AutocaptureOption.SESSIONS);
Amplitude amplitude = new Amplitude(configuration);
Amplitude enables session tracking by default. Include AutocaptureOption.SESSIONS in the autocapture configuration to explicitly configure the SDK to track session events or to enable session event tracking along with other Autocapture configurations.
import com.amplitude.android.Amplitude
val amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
autocapture = autocaptureOptions {
+sessions // or `+AutocaptureOption.SESSIONS`
}
)
)
import com.amplitude.android.Amplitude;
import java.util.Arrays;
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
// `AutocaptureOption.SESSION` is automatically set in `configuration.autocapture`.
Amplitude amplitude = new Amplitude(configuration);
For more information about session tracking, refer to User sessions.
You can enable Amplitude to start tracking application lifecycle events by including AutocaptureOption.APP_LIFECYCLES in the autocapture configuration. See the following code sample.
import com.amplitude.android.Amplitude
val amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
autocapture = autocaptureOptions {
+appLifecycles // or `+AutocaptureOption.APP_LIFECYCLES`
}
)
)
import com.amplitude.android.Amplitude;
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.getAutocapture().add(AutocaptureOption.APP_LIFECYCLES);
Amplitude amplitude = new Amplitude(configuration);
After enabling this setting, Amplitude tracks the following events:
[Amplitude] Application Installed, this event fires when a user opens the application for the first time right after installation.[Amplitude] Application Updated, this event fires when a user opens the application after updating the application.[Amplitude] Application Opened, this event fires when a user launches or foregrounds the application after the first open.[Amplitude] Application Backgrounded, this event fires when a user backgrounds the application.You can enable Amplitude to start tracking screen and fragment view events by including AutocaptureOption.SCREEN_VIEWS in the autocapture configuration. See the following code sample.
import com.amplitude.android.Amplitude
val amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
autocapture = autocaptureOptions {
+screenViews // or `+AutocaptureOption.SCREEN_VIEWS`
}
)
)
import com.amplitude.android.Amplitude;
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.getAutocapture().add(AutocaptureOption.SCREEN_VIEWS);
Amplitude amplitude = new Amplitude(configuration);
After enabling this setting, Amplitude will track both [Amplitude] Screen Viewed and [Amplitude] Fragment Viewed events. Both of these events include a screen name property. For [Amplitude] Fragment Viewed events, Amplitude captures additional fragment-specific properties.
Event properties descriptions
Event property
Description
[Amplitude] Screen NameThe activity title, activity label, activity name, activity class name, or application name (in order of priority).
[Amplitude] Fragment ClassThe fully qualified class name of the viewed fragment.
[Amplitude] Fragment IdentifierThe resource ID of the fragment as defined in the layout XML.
[Amplitude] Fragment TagThe unique identifier assigned to the fragment during a transaction.
You can enable Amplitude to start tracking deep link events by including AutocaptureOption.DEEP_LINKS in the autocapture configuration. See the following code sample.
import com.amplitude.android.Amplitude
val amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
autocapture = autocaptureOptions {
+deepLinks // or `+AutocaptureOption.DEEP_LINKS`
}
)
)
import com.amplitude.android.Amplitude;
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.getAutocapture().add(AutocaptureOption.DEEP_LINKS);
Amplitude amplitude = new Amplitude(configuration);
After enabling this setting, Amplitude will track the [Amplitude] Deep Link Opened event with the URL and referrer information.
Amplitude can track user interactions with clickable elements with support for both classic Android Views as well as Jetpack Compose. To enable this option, include AutocaptureOption.ELEMENT_INTERACTIONS in the autocapture configuration.
import com.amplitude.android.Amplitude
val amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
autocapture = autocaptureOptions {
+elementInteractions // or `+AutocaptureOption.ELEMENT_INTERACTIONS`
}
)
)
import com.amplitude.android.Amplitude;
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.getAutocapture().add(AutocaptureOption.ELEMENT_INTERACTIONS);
Amplitude amplitude = new Amplitude(configuration);
When you enable this setting, Amplitude tracks the [Amplitude] Element Interacted event whenever a user interacts with an element in the application.
Event properties descriptions
Event property
Description
[Amplitude] ActionThe action that triggered the event. Defaults to
touch.
[Amplitude] Target ClassThe canonical name of the target view class.
[Amplitude] Target ResourceThe resource entry name for the target view identifier within the context the view is running in.
[Amplitude] Target TagThe tag of the target view if the value is of primitive type, or the
Modifier.testTag of the target @Composable function if provided. This property is optional for Compose elements.
[Amplitude] Target TextThe text of the target view if the view is a
Button instance.
[Amplitude] Target SourceThe underlying framework of the target element, either
Android Views or Jetpack Compose.
[Amplitude] HierarchyA nested hierarchy of the target view's class inheritance, from the most specific to the most general.
[Amplitude] Screen NameSee Track screen views.
Modifier.testTag is optional. Add it to @Composable functions to provide additional identification in the [Amplitude] Target Tag property. If no testTag is provided, Amplitude tracks the element with other available properties.
While testTag is optional, Amplitude recommends that you identify specific Compose views that users clicked. The testTag property provides several benefits:
// Example: Adding testTag for better identification
Button(
onClick = { /* handle click */ },
modifier = Modifier.testTag("login_button")
) {
Text("Log In")
}
Card(
onClick = { /* handle click */ },
modifier = Modifier.testTag("product_card_${product.id}")
) {
// Card content
}
When a user clicks these elements, the [Amplitude] Target Tag property contains the testTag value, making it easy to identify which specific element was interacted with in your analytics data.
Amplitude can track frustration interactions (Rage Clicks and Dead Clicks) with clickable UI elements in both Android Views and Jetpack Compose. To enable this option, include AutocaptureOption.FRUSTRATION_INTERACTIONS in the autocapture configuration.
import com.amplitude.android.Amplitude
val amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
autocapture = autocaptureOptions {
+frustrationInteractions // or `+AutocaptureOption.FRUSTRATION_INTERACTIONS`
}
)
)
import com.amplitude.android.Amplitude;
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.getAutocapture().add(AutocaptureOption.FRUSTRATION_INTERACTIONS);
Amplitude amplitude = new Amplitude(configuration);
Rage Click is a click that occurs 4 or more times within 1 second on the same element, with each click no more than 50 device-independent pixels apart.
When a Rage Click occurs, Amplitude tracks the [Amplitude] Rage Click event.
Event Properties Descriptions
Event property
Description
[Amplitude] Begin TimeThe timestamp when the interaction began in ISO 8601 format.
[Amplitude] End TimeThe timestamp when the interaction ended in ISO 8601 format.
[Amplitude] DurationThe duration of the interaction in milliseconds.
[Amplitude] Click CountThe number of clicks that occurred.
[Amplitude] ClicksThe array of clicks that occurred.
[Amplitude] Clicks[].XThe x-coordinate of the click from the top-left corner of the screen.
[Amplitude] Clicks[].YThe y-coordinate of the click from the top-left corner of the screen.
[Amplitude] Clicks[].TimeThe timestamp of the click in ISO 8601 format.
[Amplitude] ActionThe action that triggered the event. Defaults to
touch.
[Amplitude] Target ClassThe canonical name of the target view class.
[Amplitude] Target ResourceThe resource entry name for the target view identifier within the context the view is running in.
[Amplitude] Target TagThe tag of the target view if the value is of primitive type, or the
Modifier.testTag of the target @Composable function if provided.
[Amplitude] Target TextThe text of the target view if the view is a
Button instance.
[Amplitude] Target SourceThe underlying framework of the target element, either
Android Views or Jetpack Compose.
[Amplitude] HierarchyA nested hierarchy of the target view's class inheritance, from the most specific to the most general.
[Amplitude] Screen NameSee Track screen views.
Dead Click is a user interaction on an interactive element that resulted in no visible change in the following 3 seconds.
When a Dead Click occurs, Amplitude tracks the [Amplitude] Dead Click event.
Event Properties Descriptions
Event property
Description
[Amplitude] XThe x-coordinate of the click from the top-left corner of the screen.
[Amplitude] YThe y-coordinate of the click from the top-left corner of the screen.
[Amplitude] ActionThe action that triggered the event. Defaults to
touch.
[Amplitude] Target ClassThe canonical name of the target view class.
[Amplitude] Target ResourceThe resource entry name for the target view identifier within the context the view is running in.
[Amplitude] Target TagThe tag of the target view if the value is of primitive type, or the
Modifier.testTag of the target @Composable function if provided.
[Amplitude] Target TextThe text of the target view if the view is a
Button instance.
[Amplitude] Target SourceThe underlying framework of the target element, either
Android Views or Jetpack Compose.
[Amplitude] HierarchyA nested hierarchy of the target view's class inheritance, from the most specific to the most general.
[Amplitude] Screen NameSee Track screen views.
Enabling FRUSTRATION_INTERACTIONS tracks both rage clicks and dead clicks. Use the interactionsOptions parameter to enable or disable each type individually.
import com.amplitude.android.Amplitude
import com.amplitude.android.InteractionsOptions
import com.amplitude.android.RageClickOptions
import com.amplitude.android.DeadClickOptions
val amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
autocapture = autocaptureOptions {
+frustrationInteractions
},
interactionsOptions = InteractionsOptions(
rageClick = RageClickOptions(enabled = true),
deadClick = DeadClickOptions(enabled = false)
)
)
)
import com.amplitude.android.Amplitude;
import com.amplitude.android.InteractionsOptions;
import com.amplitude.android.RageClickOptions;
import com.amplitude.android.DeadClickOptions;
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.getAutocapture().add(AutocaptureOption.FRUSTRATION_INTERACTIONS);
configuration.setInteractionsOptions(
new InteractionsOptions(
new RageClickOptions(true),
new DeadClickOptions(false)
)
);
Amplitude amplitude = new Amplitude(configuration);
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.
groupName would be '15'.
// set group with a single group name
amplitude.setGroup("orgId", "15");
If Joe is in 'sport' 'tennis' and 'soccer', then the groupName would be '["tennis", "soccer"]'.
// set group with multiple group names
amplitude.setGroup("sport", arrayOf("tennis", "soccer"))
You can also set event-level groups by passing an Event Object with groups to track. With event-level groups, the group designation applies only to the specific event being logged, and doesn't persist on the user unless you explicitly set it with setGroup.
val event = BaseEvent()
event.eventType = "event type"
event.eventProperties = mutableMapOf("event property" to "event property value")
event.groups = mutableMapOf("orgId" to "15")
amplitude.track(event)
Use the Group Identify API to set or update the properties of particular groups. Keep these considerations in mind:
The groupIdentify method accepts a group type string parameter and group name object parameter, and an Identify object that's applied to the group.
val groupType = "plan"
val groupName = "enterprise"
val identify = Identify().set("key", "value")
amplitude.groupIdentify(groupType, groupName, identify)
Amplitude can track revenue generated by a user. Revenue is tracked through distinct revenue objects, which have special fields that are used in Amplitude's Event Segmentation and Revenue LTV charts. This allows Amplitude to automatically display data relevant to revenue in the platform. Revenue objects support the following special properties, as well as user-defined properties through the eventProperties field.
val revenue = Revenue()
revenue.productId = "com.company.productId"
revenue.price = 3.99
revenue.quantity = 3
amplitude.revenue(revenue)
| Name | Description |
|---|---|
productId |
Optional. String. An identifier for the product. Amplitude recommends something like the Google Play Store product ID. Defaults to null. |
quantity |
Required. Integer. The quantity of products purchased. revenue = quantity * price. Defaults to 1 |
price |
Required. Double. The price of the products purchased, and this can be negative. revenue = quantity * price. Defaults to null. |
revenueType |
Optional, but required for revenue verification. String. The revenue type (for example, tax, refund, income). Defaults to null. |
receipt |
Optional. String. The receipt identifier of the revenue. For example, 123456. Defaults to null. |
receiptSignature |
Optional, but required for revenue verification. String. Defaults to null. |
If your app has its login system that you want to track users with, you can call setUserId at any time.
amplitude.setUserId("user@amplitude.com")
You can assign a new device ID using deviceId. When setting a custom device ID, make sure the value is sufficiently unique. Amplitude recommends using a UUID.
import java.util.UUID
amplitude.setDeviceId(UUID.randomUUID().toString())
reset is a shortcut to anonymize users after they log out, by:
userId to nulldeviceId to a new value based on current configurationWith an empty userId and a completely new deviceId, the current user would appear as a brand new user in dashboard.
amplitude.reset()
Plugins allow you to extend Amplitude SDK's behavior by, for example, modifying event properties (enrichment type) or sending to third-party APIs (destination type). A plugin is an object with methods setup() and execute().
This method contains logic for preparing the plugin for use and has amplitude instance as a parameter. The expected return value is null. A typical use for this method, is to instantiate plugin dependencies. This method is called when the plugin is registered to the client via amplitude.add().
This method contains the logic for processing events and has event instance as parameter. If used as enrichment type plugin, the expected return value is the modified/enriched event. If used as a destination type plugin, the expected return value is a map with keys: event (BaseEvent), code (number), and message (string). This method is called for each event, including Identify, GroupIdentify and Revenue events, that's instrumented using the client interface.
Here's an example of a plugin that modifies each event that's instrumented by adding extra event property.
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.amplitude.core.Amplitude;
import com.amplitude.core.events.BaseEvent;
import com.amplitude.core.platform.Plugin;
import java.util.HashMap;
public class EnrichmentPlugin implements Plugin {
public Amplitude amplitude;
@NonNull
@Override
public Amplitude getAmplitude() {
return this.amplitude;
}
@Override
public void setAmplitude(@NonNull Amplitude amplitude) {
this.amplitude = amplitude;
}
@NonNull
@Override
public Type getType() {
return Type.Enrichment;
}
@Nullable
@Override
public BaseEvent execute(@NonNull BaseEvent baseEvent) {
if (baseEvent.getEventProperties() == null) {
baseEvent.setEventProperties(new HashMap<String, Object>());
}
baseEvent.getEventProperties().put("custom android event property", "test");
return baseEvent;
}
@Override
public void setup(@NonNull Amplitude amplitude) {
this.amplitude = amplitude;
}
}
amplitude.add(new EnrichmentPlugin());
In a destination plugin, you can overwrite the track(), identify(), groupIdentify(), revenue(), flush() functions.
import com.amplitude.core.Amplitude;
import com.amplitude.core.events.BaseEvent;
import com.amplitude.core.platform.DestinationPlugin;
import com.segment.analytics.Analytics;
import com.segment.analytics.Properties;
public class SegmentDestinationPlugin extends DestinationPlugin {
android.content.Context context;
Analytics analytics;
String writeKey;
public SegmentDestinationPlugin(android.content.Context appContext, String writeKey) {
this.context = appContext;
this.writeKey = writeKey;
}
@Override
public void setup(Amplitude amplitude) {
super.setup(amplitude);
analytics = new Analytics.Builder(this.context, this.writeKey)
.build();
Analytics.setSingletonInstance(analytics);
}
@Override
public BaseEvent track(BaseEvent event) {
Properties properties = new Properties();
for (Map.Entry<String,Object> entry : event.getEventProperties().entrySet()) {
properties.putValue(entry.getKey(),entry.getValue());
}
analytics.track(event.eventType, properties);
return event;
}
}
amplitude.add(
new SegmentDestinationPlugin(this, SEGMENT_WRITE_KEY)
)
The Network Tracking Plugin allows you to automatically track network requests and responses in your application. This plugin works with OkHttp, capturing details about network calls including URLs, status codes, and timing information.
The Network Tracking Plugin requires the OkHttp dependency. To add it to your project:
dependencies {
// OkHttp is required for the NetworkTrackingPlugin
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
}
Use the default configuration and add the plugin as an interceptor to integrate with OkHttp:
import com.amplitude.core.network.NetworkTrackingPlugin
// Create the plugin with default configuration
val networkPlugin = NetworkTrackingPlugin()
// Add the plugin as an interceptor to your OkHttp client
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(networkPlugin)
.build()
// Add the plugin to your Amplitude instance
amplitude.add(networkPlugin)
import com.amplitude.core.network.NetworkTrackingPlugin;
// Create the plugin with default configuration
NetworkTrackingPlugin networkPlugin = new NetworkTrackingPlugin();
// Add the plugin as an interceptor to your OkHttp client
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(networkPlugin)
.build();
// Add the plugin to your Amplitude instance
amplitude.add(networkPlugin);
The default configuration tracks all hosts except *.amplitude.com with status code 500 to 599.
NetworkTrackingOptions.DEFAULT
Name
Description
Value
captureRulesCaptures all hosts (except
*.amplitude.com) with status code 500 to 599.NetworkTrackingOptions(captureRules = listOf(CaptureRule(hosts = listOf("*"), statusCodeRange = (500..599).toList())))
ignoreHostsDon't ignore any other hosts by default.
[]
ignoreAmplitudeRequestsDon't capture Amplitude requests by default.
true
Set NetworkTrackingOptions to customize the tracking behavior and control which requests you track:
import com.amplitude.android.Amplitude
import com.amplitude.core.network.NetworkTrackingOptions
import com.amplitude.core.network.NetworkTrackingPlugin
import com.amplitude.core.network.NetworkTrackingOptions.CaptureRule
// Create custom capture rules
val options = NetworkTrackingOptions(
captureRules = listOf(
// Track all responses from your API domain with status code from 400 to 599
CaptureRule(
hosts = listOf("*.example.com", "example.com"),
statusCodeRange = (400..599).toList()
)
),
// Ignore specific domains
ignoreHosts = listOf("analytics.example.com", "*.internal.com"),
// Whether to ignore Amplitude API requests
ignoreAmplitudeRequests = true
)
// Create the plugin with options
val networkPlugin = NetworkTrackingPlugin(options)
// Add the plugin to your Amplitude instance
amplitude.add(networkPlugin)
import com.amplitude.android.Amplitude;
import com.amplitude.core.network.NetworkTrackingOptions;
import com.amplitude.core.network.NetworkTrackingPlugin;
import com.amplitude.core.network.NetworkTrackingOptions.CaptureRule;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
NetworkTrackingOptions options = new NetworkTrackingOptions(
// Create custom capture rules
Collections.singletonList(
new NetworkTrackingOptions.CaptureRule(
// Track all responses from your API domain with status code from 400 to 599
Arrays.asList("*.example.com", "example.com"),
new ArrayList<Integer>() {
{ for (int i = 400; i <= 599; i++) add(i); }
}
)
),
// Ignore specific domains
Arrays.asList("analytics.example.com", "*.internal.com"),
// Whether to ignore Amplitude API requests
true
);
// Create the plugin with options
NetworkTrackingPlugin networkPlugin = new NetworkTrackingPlugin(options);
// Add the plugin to your Amplitude instance
amplitude.add(networkPlugin);
NetworkTrackingOptions
Name
Description
Default Value
captureRulesThe rules for capturing network requests. You should always append rules with specific hosts to the bottom of the list.
none
ignoreHostsThe hosts to ignore. Supports wildcard characters
*. For example, ["*"] ignores all hosts, ["*.notmyapi.com", "notmyapi.com"] ignores notmyapi.com and all subdomains.[]
ignoreAmplitudeRequestsWhether to ignore Amplitude requests.
true
NetworkTrackingOptions.CaptureRule
Name
Description
Default Value
hostsThe hosts to capture. Supports wildcard characters
*. For example, ["*"] matches all hosts, ["*.example.com", "example.com"] matches example.com and all subdomains.none
statusCodeRangeThe status code range to capture. For example,
(200..299) + 413 + (500..599)"500-599"
captureRules and ignoreHosts properties are mutually exclusive. If both are set, ignoreHosts takes precedence. Amplitude matches incoming requests against the captureRules from bottom to top. For example, with this configuration:
captureRules = listOf(
CaptureRule(
hosts = listOf("\*"),
statusCodeRange = (400..599).toList()
),
CaptureRule(
hosts = listOf("\*.example.com", "example.com"),
statusCodeRange = (500..599).toList()
)
)
The SDK processes requests as follows:
example.com with status code 503: matches last rule's hosts → matches statusCodeRange → capturedexample.com with status code 401: matches last rule's hosts → doesn't match statusCodeRange → ignoredother.com with status code 401: doesn't match last rule's hosts → matches first rule's hosts → matches statusCodeRange → capturedother.com with status code 200: doesn't match last rule's hosts → matches first rule's hosts → doesn't match statusCodeRange → ignoredWhen the plugin tracks a network request, it sends an event with the type [Amplitude] Network Request with the following properties:
| Property | Description |
|---|---|
[Amplitude] URL |
The URL of the network request with sensitive information masked. |
[Amplitude] URL Query |
The query parameters of the URL. |
[Amplitude] URL Fragment |
The fragment identifier of the URL. |
[Amplitude] Request Method |
The HTTP method used for the request (GET, POST, etc.). |
[Amplitude] Status Code |
The HTTP status code of the response. |
[Amplitude] Error Message |
The local error message if the request failed with out a status code. |
[Amplitude] Start Time |
The timestamp when the request started, in milliseconds since Unix epoch. |
[Amplitude] Completion Time |
The timestamp when the request completed, in milliseconds since Unix epoch. |
[Amplitude] Duration |
The duration of the request in milliseconds. |
[Amplitude] Request Body Size |
The size of the request body in bytes. |
[Amplitude] Response Body Size |
The size of the response body in bytes. |
The Network Tracking Plugin masks the following sensitive information by default:
Ensure that the configuration and payload are accurate and check for any unusual messages during the debugging process. If everything appears to be right, check the value of flushQueueSize or flushIntervalMillis. Events are queued and sent in batches by default, which means they don't dispatch to the server. Ensure that you have waited for the events to be sent to the server before checking for them in the charts.
loggerProvider class from the LoggerProvider and implement your own logic, such as logging error message in server in a production environment.You can take advantage of a destination plugin to print out the configuration value and event payload before sending them to the server. You can set the logLevel to debug, copy the following TroubleShootingPlugin into your project, add the plugin into the Amplitude instance.
The event callback executes after the event is sent, for both successful and failed events. Use this method to monitor the event status and message. For more information, the Callback configuration setting.
Amplitude starts a session when the app is brought into the foreground or when an event is tracked in the background. A session ends when the app remains in the background for more than the time set by setMinTimeBetweenSessionsMillis() without any event being tracked. Note that a session will continue for the entire time the app is in the foreground no matter whether session tracking is enabled by configuration.trackingSessionEvents, configuration.defaultTracking, configuration.autocapture or not.
When the app enters the foreground, Amplitude tracks a session start, and starts a countdown based on setMinTimeBetweenSessionsMillis(). Amplitude extends the session and restarts the countdown any time it tracks a new event. If the countdown expires, Amplitude waits until the next event to track a session end event.
Amplitude doesn't set user properties on session events by default. To add these properties, use identify() and setUserId(). Amplitude aggregates the user property state and associates the user with events based on device_id or user_id.
Due to the way in which Amplitude manages sessions, there are scenarios where the SDK works expected but it may appear as if events are missing or session tracking is inaccurate:
event['$skip_user_properties_sync'] to true on the session end event, which prevents Amplitude from synchronizing properties for that specific event. See $skip_user_properties_sync in the Converter Configuration Reference article to learn more.Amplitude groups events together by session. Events that are logged within the same session have the same session_id. Sessions are handled automatically so you don't have to manually call startSession() or endSession().
You can adjust the time window for which sessions are extended. The default session expiration time is 30 minutes.
amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
minTimeBetweenSessionsMillis = 10000
)
)
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.setMinTimeBetweenSessionsMillis(1000);
Amplitude amplitude = new Amplitude(configuration);
By default, Amplitude automatically sends the '[Amplitude] Start Session' and '[Amplitude] End Session' events. Even though these events aren't sent, sessions are still tracked by using session_id.
You can also disable those session events.
amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
autocapture = setOf()
)
)
amplitude = AmplitudeKt.Amplitude(AMPLITUDE_API_KEY, getApplicationContext(), configuration -> {
configuration.getAutocapture().remove(AutocaptureOption.SESSION);
return Unit.INSTANCE;
});
Use the helper method getSessionId to get the value of the current sessionId.
amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
minTimeBetweenSessionsMillis = 10000
)
)
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.setMinTimeBetweenSessionsMillis(10000);
Amplitude amplitude = new Amplitude(configuration);
You can also track events as out-of-session. Out-of-session events have a sessionId of -1 and behave as follows:
sessionId for subsequent events.A potential use case is for events tracked from push notifications, which are usually external to the customers app usage.
Set the sessionId to -1 in EventOptions to mark an event as out-of-session when you call track(event, options) or identify(identify, options).
val outOfSessionOptions = EventOptions().apply {
sessionId = -1
}
amplitude.identify(
Identify().set("user-prop", true),
outOfSessionOptions
)
amplitude.track(
BaseEvent().apply { eventType = "test event" },
outOfSessionOptions
)
EventOptions outOfSessionOptions = new EventOptions();
outOfSessionOptions.setSessionId(-1L);
amplitude.identify(
new Identify().set("user-prop", true),
outOfSessionOptions
);
BaseEvent event = new BaseEvent();
event.eventType = "test event";
amplitude.track(event, outOfSessionOptions);
Control the level of logs that print to the developer console.
INFO: Shows informative messages about events.WARN: Shows error messages and warnings. This level logs issues that might be a problem and cause some oddities in the data. For example, this level would display a warning for properties with null values.ERROR: Shows error messages only.DISABLE: Suppresses all log messages.DEBUG: Shows error messages, warnings, and informative messages that may be useful for debugging.Set the log level by calling setLogLevel with the level you want.
amplitude.logger.logMode = Logger.LogMode.DEBUG
amplitude.getLogger().setLogMode(Logger.LogMode.DEBUG);
Amplitude merges user data, so any events associated with a known userId or deviceId are linked the existing user.
If a user logs out, Amplitude can merge that user's logged-out events to the user's record. You can change this behavior and log those events to an anonymous user instead.
To log events to an anonymous user:
userId to null.deviceId.Events coming from the current user or device appear as a new user in Amplitude. Note: If you do this, you can't see that the two users were using the same device.
amplitude.reset()
By default the Android SDK tracks several user properties such as carrier, city, country, ip_address, language, and platform.
Use the provided TrackingOptions interface to customize and toggle individual fields.
To use the TrackingOptions interface, import the class.
import com.amplitude.android.TrackingOptions
Before initializing the SDK with your apiKey, create a TrackingOptions instance with your configuration and set it on the SDK instance.
val trackingOptions = TrackingOptions()
trackingOptions.disableCity().disableIpAddress().disableLatLng()
amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
trackingOptions = trackingOptions
)
)
TrackingOptions trackingOptions = new TrackingOptions();
trackingOptions.disableCity().disableIpAddress().disableLatLng();
// init instance
amplitude = AmplitudeKt.Amplitude(AMPLITUDE_API_KEY, getApplicationContext(), configuration -> {
configuration.setTrackingOptions(trackingOptions);
return Unit.INSTANCE;
});
Tracking for each field can be individually controlled, and has a corresponding method (for example, disableCountry, disableLanguage).
| Method | Description |
|---|---|
disableAdid() |
Disable tracking of Google ADID |
disableAppSetId() |
Disable tracking of App Set Id |
disableCarrier() |
Disable tracking of device's carrier |
disableCity() |
Disable tracking of user's city |
disableCountry() |
Disable tracking of user's country |
disableDeviceBrand() |
Disable tracking of device brand |
disableDeviceModel() |
Disable tracking of device model |
disableTrackDeviceManufacturer() |
Disable tracking of device manufacturer |
disableDma() |
Disable tracking of user's designated market area (DMA). |
disableIpAddress() |
Disable tracking of user's IP address |
disableLanguage() |
Disable tracking of device's language |
disableLatLng() |
Disable tracking of user's current latitude and longitude coordinates |
disableOsName() |
Disable tracking of device's OS Name |
disableOsVersion() |
Disable tracking of device's OS Version |
disablePlatform() |
Disable tracking of device's platform |
disableRegion() |
Disable tracking of user's region. |
disableVersionName() |
Disable tracking of your app's version name |
disableApiLevel |
Disable tracking of Android API level |
TrackingOptions only prevents default properties from being tracked on newly created projects, where data has not yet been sent. If you have a project with existing data that you want to stop collecting the default properties for, get help in the Amplitude Community. Disabling tracking doesn't delete any existing data in your project.Amplitude determines the user's mobile carrier using Android's TelephonyManager networkOperatorName, which returns the current registered operator of the tower.
COPPA (Children's Online Privacy Protection Act) restrictions on IDFA, IDFV, city, IP address and location tracking can all be enabled or disabled at one time. Apps that ask for information from children under 13 years of age must comply with COPPA.
amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
enableCoppaControl = true //Disables ADID, city, IP, and location tracking
)
)
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
//Disables ADID, city, IP, and location tracking
configuration.setEnableCoppaControl(true);
Amplitude amplitude = new Amplitude(configuration);
The Android Advertising ID is a unique identifier provided by the Google Play store. As it's unique to every person and not just their devices, it's useful for mobile attribution. This is similar to the IDFA on iOS.
Mobile attribution is the attribution of an installation of a mobile app to its original source (such as ad campaign, app store search).
Users can choose to disable the Advertising ID, and apps targeted to children can't track at all.
Follow these steps to use Android Ad ID.
Add play-services-ads-identifier as a dependency.
dependencies {
implementation 'com.google.android.gms:play-services-ads-identifier:18.0.1'
}
AD_MANAGER_APP Permission
If you use Google Mobile Ads SDK version 17.0.0 or higher, you need to add AD_MANAGER_APP to AndroidManifest.xml.
<manifest>
<application>
<meta-data
android:name="com.google.android.gms.ads.AD_MANAGER_APP"
android:value="true"/>
</application>
</manifest>
Add ProGuard exception
Amplitude Android SDK uses Java Reflection to use classes in Google Play Services. For Amplitude SDKs to work in your Android application, add these exceptions to proguard.pro for the classes from play-services-ads.
-keep class com.google.android.gms.ads.** { *; }
AD_ID Permission
When apps update their target to Android 13 or above will need to declare a Google Play services normal permission in the manifest file as follows if you are trying to use the ADID as a deviceId:
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>
Learn More here.
After you set up the logic to fetch the advertising ID, you can enable useAdvertisingIdForDeviceId to use advertising id as the device ID.
amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
useAdvertisingIdForDeviceId = true
)
)
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.setUseAdvertisingIdForDeviceId(true);
Amplitude amplitude = new Amplitude(configuration);
App set ID is a unique identifier for each app install on a device. App set ID is reset by the user manually when they uninstall the app, or after 13 months of not opening the app.
Google designed this as a privacy-friendly alternative to Ad ID for users who want to opt out of stronger analytics.
To use app set ID, follow these steps.
Add play-services-appset as a dependency. For versions earlier than 2.35.3, use 'com.google.android.gms:play-services-appset:16.0.0-alpha1'
dependencies {
implementation 'com.google.android.gms:play-services-appset:16.0.2'
}
Enable to use app set ID as Device ID.
amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
useAppSetIdForDeviceId = true
)
)
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.setUseAppSetIdForDeviceId(true);
Amplitude amplitude = new Amplitude(configuration);
The SDK initializes the device ID in the following order, with the device ID being set to the first valid value encountered:
useAdvertisingIdForDeviceId is enabled and required module is installed. Learn moreS appended if useAppSetIdForDeviceId is enabled and required module is installed. Learn moreR appendedA single user may have multiple devices, each having a different device ID. To ensure coherence, set the user ID consistently across all these devices. Even though the device IDs differ, Amplitude can still merge them into a single Amplitude ID, thus identifying them as a unique user.
It's possible for multiple devices to have the same device ID when a user switches to a new device. When transitioning to a new device, users often transfer their applications along with other relevant data. The specific transferred content may vary depending on the application. In general, it includes databases and file directories associated with the app. However, the exact items included depend on the app's design and the choices made by the developers. If databases or file directories have been backed up from one device to another, the device ID stored within them may still be present. If the SDK attempts to retrieve it during initialization, different devices might end up using the same device ID.
Use the helper method getDeviceId() to get the value of the current deviceId.
val deviceId = amplitude.getDeviceId();
String deviceId = amplitude.getDeviceId();
To set the device, see to custom device ID.
Amplitude converts the IP of a user event into a location (GeoIP lookup) by default. This information may be overridden by an app's own tracking solution or user data.
enableLocationListening() to track location data. When enabled, Amplitude uses Android location services (if available) to add specific coordinates (longitude and latitude) to logged events. Call disableLocationListening() at any time to disable location tracking.
amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
locationListening = true
)
)
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.setLocationListening(true);
Amplitude amplitude = new Amplitude(configuration);
-keep class com.google.android.gms.common.** { *; }Users may wish to opt out of tracking entirely, which means Amplitude doesn't track any of their events or browsing history. OptOut provides a way to fulfill a user's requests for privacy.
amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
optOut = true
)
)
Configuration configuration = new Configuration(AMPLITUDE_API_KEY, getApplicationContext());
configuration.setOptOut(true);
Amplitude amplitude = new Amplitude(configuration);
Don't send push notification events client-side with the Android SDK. Because a user must open the app to initialize the Amplitude SDK in order for the SDK to send the event, events aren't sent to the Amplitude servers until the next time the user opens the app. This can cause data delays.
import com.amplitude.common.Logger
import com.amplitude.core.LoggerProvider
class sampleLogger : Logger {
override var logMode: Logger.LogMode
get() = Logger.LogMode.DEBUG
set(value) {}
override fun debug(message: String) {
TODO("Handle debug message here")
}
override fun error(message: String) {
TODO("Handle error message here")
}
override fun info(message: String) {
TODO("Handle info message here")
}
override fun warn(message: String) {
TODO("Handle warn message here")
}
}
class sampleLoggerProvider : LoggerProvider {
override fun getLogger(amplitude: com.amplitude.core.Amplitude): Logger {
return sampleLogger()
}
}
amplitude = Amplitude(
Configuration(
apiKey = AMPLITUDE_API_KEY,
context = applicationContext,
loggerProvider = sampleLoggerProvider()
)
)
import com.amplitude.common.Logger;
import com.amplitude.core.LoggerProvider;
class sampleLogger implements Logger {
@NonNull
@Override
public LogMode getLogMode() {
return LogMode.DEBUG;
}
@Override
public void setLogMode(@NonNull LogMode logMode) {
// TODO("Handle debug message here")
}
@Override
public void debug(@NonNull String message) {
// TODO("Handle debug message here")
}
@Override
public void error(@NonNull String message) {
// TODO("Handle error message here")
}
@Override
public void info(@NonNull String message) {
// TODO("Handle info message here")
}
@Override
public void warn(@NonNull String message) {
// TODO("Handle warn message here")
}
}
class sampleLoggerProvider implements LoggerProvider {
@NonNull
@Override
public Logger getLogger(@NonNull com.amplitude.core.Amplitude amplitude) {
return new sampleLogger();
}
}
You can create multiple instances of Amplitude. Instances with the same instanceName share storage and identity. For isolated storage and identity use a unique instanceName for each instance. For more details see Configuration.
val amplitude1 = Amplitude(Configuration(
instanceName = "one",
apiKey = "api-key-1",
context = applicationContext,
))
val amplitude2 = Amplitude(Configuration(
instanceName = "two",
apiKey = "api-key-2",
context = applicationContext,
))
Starting from version 1.13.0, the Amplitude Android Kotlin SDK supports offline mode. The SDK checks network connectivity every time it tracks an event. If the device is connected to network, the SDK schedules a flush. If not, it saves the event to storage. The SDK also listens for changes in network connectivity and flushes all stored events when the device reconnects.
To enable this feature, add the ACCESS_NETWORK_STATE permission to AndroidManifest.xml. Otherwise, the SDK flushes the event based on flushIntervalMillis and flushQueueSize.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You can also implement you own offline logic:
config.offline to AndroidNetworkConnectivityCheckerPlugin.Disabled to disable the default offline logic.config.offline by yourselfJuly 23rd, 2024
Need help? Contact Support
Visit Amplitude.com
Have a look at the Amplitude Blog
Learn more at Amplitude Academy
© 2025 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.