---
title: Android Client SDK
description: "Statsig's SDK for Experimentation and Feature Flags in Java & Kotlin Android applications."
product: general
token_estimate: 5373
---
# Android Client SDK

> For AI agents: a documentation index is available at [/llms.txt](/llms.txt). Append `.md` to any page URL for markdown, or send `Accept: text/markdown`.

- **Package:** `com.statsig:android-sdk` ([maven](https://search.maven.org/artifact/com.statsig/android-sdk))
- **Latest version:** 5.1.4
- **Repository:** [android-sdk](https://github.com/statsig-io/android-sdk)

## Set up the SDK

1. **Install the SDK**

   v4.37.1 and higher are published to only [Maven Central](https://central.sonatype.com/artifact/com.statsig/android-sdk). To install the SDK, set the Maven Central repository in your build.gradle.

   ```java
   dependencies {
       implementation "com.statsig:android-sdk:4.37.1"
   }
   ```

   You can install legacy versions (<=V4.37.0) with [Jitpack](https://jitpack.io/#statsig-io/android-sdk).
2. **Initialize the SDK**

   Next, initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application.

   Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later in a gate or experiment.

   #### MainActivity.java

   ```java
   import com.statsig.androidsdk.*;
   ...

   public class MainActivity extends AppCompatActivity implements IStatsigCallback {

       ...
       StatsigOptions options = new StatsigOptions();
       options.setTier(Tier.PRODUCTION);
       StatsigUser user = new StatsigUser("UUID");
       Statsig.initializeAsync(app, "client-key", user, this, options);
       ...
       // SDK is usable, but values will be from the cache or defaults (false for gates, {} for configs)
       // Once onStatsigInitialize fires, then


       @Override
       public void onStatsigInitialize() {
           // SDK is initialized and has the most up to date values
       }

       @Override
       public void onStatsigUpdateUser() {
           // User has been updated and values have been refetched for the new user
       }

   }
   ```

   #### MainActivity.kt

   ```kotlin
   import com.statsig.androidsdk.*

   ...

   async {
       Statsig.initialize(
           this.application,
           "my_client_sdk_key",
           StatsigUser("user_id"),
       )
   }.await()
   ```

## Use the SDK

### Checking a Feature Flag/Gate

After the SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (equivalent to `return false;`) by default.

#### Java

```java
DynamicConfig config = Statsig.getConfig("awesome_product_details");

// The 2nd parameter is the default value to be used in case the given parameter name does not exist on
// the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the
// value has not been cached on the client.
String itemName = config.getString("product_name", "Awesome Product v1");
Double price = config.getDouble("price", 10.0);
Boolean shouldDiscount = config.getBoolean("discount", false);
```

#### Kotlin

```kotlin
val config = Statsig.getConfig("awesome_product_details")

// The 2nd parameter is the default value to be used in case the given parameter name does not exist on
// the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the
// value has not been cached on the client.
val itemName = config.getString("product_name", "Awesome Product v1")
val price = config.getDouble("price", 10.0)
val shouldDiscount = config.getBoolean("discount", false)
```

### Reading a Dynamic Config

Feature Gates work well for simple on/off switches with optional advanced user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates, but returns an entire JSON object you configure on the server, from which you can fetch typed parameters. For example:

#### Java

```java
if (Statsig.checkGate("new_homepage_design")) {
  // Gate is on, show new home page
} else {
  // Gate is off, show old home page
}
```

#### Kotlin

```kotlin
if (Statsig.checkGate("new_homepage_design")) {
  // Gate is on, show new home page
} else {
  // Gate is off, show old home page
}
```

### Getting a Layer/Experiment

**Layers/Experiments** support running A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse.

#### Java

```java
// Values via getLayer

Layer layer = Statsig.getLayer("user_promo_experiments")
String promoTitle = layer.getString("title", "Welcome to Statsig!");
Double discount = layer.getDouble("discount", 0.1);

// or, via getExperiment

DynamicConfig titleExperiment = Statsig.getExperiment("new_user_promo_title");
DynamicConfig priceExperiment = Statsig.getExperiment("new_user_promo_price");

String promoTitle = titleExperiment.getString("title", "Welcome to Statsig!");
Double discount = priceExperiment.getDouble("discount", 0.1);

...

Double price = msrp * (1 - discount);
```

#### Kotlin

```kotlin
// Values via getLayer

val layer = Statsig.getLayer("user_promo_experiments")
val promoTitle = layer.getString("title", "Welcome to Statsig!")
val discount = layer.getDouble("discount", 0.1)

// or, via getExperiment

val titleExperiment = Statsig.getExperiment("new_user_promo_title")
val priceExperiment = Statsig.getExperiment("new_user_promo_price")

val promoTitle = titleExperiment.getString("title", "Welcome to Statsig!")
val discount = priceExperiment.getDouble("discount", 0.1)

...

val price = msrp * (1 - discount);
```

### Logging an Event

After setting up a Feature Gate or an Experiment, you can track custom events to see how your new features or different experiment groups affect those events. Call the Log Event API for the event, and optionally provide a value and metadata object to log with the event:

#### Java

```java
Statsig.logEvent("purchase", 2.99, Map.of("item_name", "remove_ads"));
```

#### Kotlin

```kotlin
Statsig.logEvent("purchase", 2.99, Map.of("item_name" to "remove_ads"))
```

## Parameter Stores

Parameter Stores hold a set of parameters for your mobile app. These parameters can be remapped dynamically from a static value to a Statsig entity (Feature Gates, Experiments, and Layers). Remapping lets you decouple your code from the configuration in Statsig. Refer to [Param Stores](https://docs.statsig.com/client/concepts/parameter-stores) for more information.

### Getting a parameter store

To fetch a set of parameters, use the following API:

#### Java

```java
ParameterStore homepageStore = Statsig.getParameterStore("homepage");
```

#### Kotlin

```kotlin
val homepageStore = Statsig.getParameterStore("homepage")
```

### Getting a parameter

You can then access parameters like this:

#### Java

```java
String title = homepageStore.getString(
    "title", //parameter name
    "Welcome" // default value
);

boolean shouldShowUpsell = homePageStore.getBoolean("upsell_upgrade_now", false);
```

#### Kotlin

```kotlin
val title = homepageStore.getString(
  "title",   // parameter name
  "Welcome", // default value
)

val shouldShowUpsell = homepageStore.getBoolean("upsell_upgrade_now", false)
```

## Statsig User

You need to provide a StatsigUser object to check or get your configurations. Pass as much information as possible to take advantage of advanced gate and config conditions.

The `userID` field is required in most cases to provide a consistent experience for a given user (refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) for how to run experiments for logged-out users).

In addition to `userID`, StatsigUser offers the following top-level fields: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object or dictionary to the `custom` field to create targeting based on them.

After the user logs in or their attributes change, call `updateUser` with the updated `userID` and any other updated user attributes:

#### Java

```java
StatsigUser newUser = new StatsigUser("new_user_id");
Statsig.updateUserAsync(newUser, this); // this must implement IStatsigCallback

...

@Override
public void onStatsigUpdateUser() {
    // User has been updated and values have been refetched for the new user
}
```

#### Kotlin

```kotlin
Statsig.updateUser(StatsigUser("new_user_id"))
```

### Private attributes

To prevent logging sensitive user PII, use the `privateAttributes` field on the StatsigUser object. Statsig uses any attribute set in `privateAttributes` only for evaluation and targeting, and removes it from logs before sending them to the server.

For example, suppose you have feature gates that should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig. In that case, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user.

## Statsig Options

Pass an optional `options` parameter in addition to `sdkKey` and `user` during initialization to customize the Statsig client.

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| api | String | No | — | Default endpoint for all SDK network requests. Don't override unless you implement the Statsig API elsewhere. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| disableCurrentActivityLogging | Boolean | No | — | Include the current top-level activity on logged events by default. Set to `true` to disable. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| disableDiagnosticsLogging | Boolean | No | — | Deprecated. Previously prevented the SDK from sending diagnostic information. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| initTimeoutMs | Long | No | — | Milliseconds to wait for the initial request before completing. Set to `0` to wait indefinitely. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| enableAutoValueUpdate | Boolean | No | — | Periodically fetch updated values for the current user when enabled. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| autoValueUpdateIntervalMinutes | Double | No | — | Frequency (in minutes) for auto value refresh. Minimum is `1` minute. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| overrideStableID | String? | No | — | Override the SDK-generated `stableID` for the user. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| loadCacheAsync | Boolean | No | — | Whether the SDK should block on loading saved values from disk. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| initializeValues | Map<String, Any>? | No | — | Provide the initialize response directly to bootstrap the client synchronously. Go to the NodeJS Server SDK for generating values and the Bootstrap docs. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| disableHashing | Boolean? | No | — | When `true`, gate/config/experiment names aren't hashed and remain readable. Requires special authorization from Statsig. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| customCacheKey | ((sdkKey: String, user: StatsigUser) -> String) | No | — | Override how Statsig generates the cache key for stored values when the default doesn't fit your needs. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| evaluationCallback | ((config: BaseConfig) -> Unit) | No | — | Callback invoked whenever you check a gate, config, experiment, or layer. Receives the evaluated `BaseConfig`. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| lifetimeCallback | IStatsigLifetimeCallback? | No | — | Callbacks that may trigger multiple times over the lifetime of the client SDK. The SDK calls them on the main thread.- `onValuesUpdated()` - called when new values are received and available for use. May be called after `Statsig.updateUser()`, `Statsig.updateUserAsync()`, or auto value updates (refer to `enableAutoValueUpdate`) |

#### Methods

- **setTier | setEnvironmentParameter | getEnvironment**

  - signals the environment tier the user is in.
  - `setTier` can be PRODUCTION, STAGING or DEVELOPMENT. For example, passing a value of `Tier.STAGING` lets your users pass any condition that passes for the staging environment tier. Those users fail any condition that only passes for other environment tiers.
  - use `setEnvironmentParameter` for custom tiers, for example `options.setEnvironmentParameter("tier", "test")`

#### Runtime options

Starting in `V4.43.0`, you can set a subset of options during initialization and later update them while the Statsig client is running.

`StatsigRuntimeMutableOptions` (which `StatsigOptions` extends) defines these options.

Call `Statsig.updateRuntimeOptions(runtimeMutableOptions: StatsigRuntimeMutableOptions)` or the corresponding method in `StatsigClient` to update the Statsig client with new values.

- **loggingEnabled**: `Boolean`, default `true`

  - Setting this value to `false` prevents the Statsig client from sending logging events over the network or saving events to its on-disk cache. The Statsig client queues the 1000 most recent events in memory. You can log them to network (or cache them) by setting `loggingEnabled` to `true` later during that session.
  - Calling `Statsig.flush()` after setting `loggingEnabled` to `true` immediately clears the queue and minimizes loss of older log events.
  - This is useful for cases where users must grant permission before you log events, or any other case where you shouldn't enable logging.

## Shutting Statsig down

To save data and battery usage and avoid dropping logged events, the SDK keeps event logs in client cache and flushes them periodically. Because of this periodic flushing, the SDK may not have sent some events when your app shuts down.

To ensure the SDK flushes or saves all logged events locally, call `shutdown` when your app is closing:

#### Java

```java
Statsig.shutdown();
```

#### Kotlin

```kotlin
Statsig.shutdown()
```

## Using persistent evaluations

To ensure that a user's variant stays consistent while an experiment is running, regardless of changes to allocation or targeting, use persistent storage. The Android SDK supports a minimal implementation using the keepDeviceValues flag. Refer to the [Client Persistent Assignment Doc](https://docs.statsig.com/client/concepts/persistent_assignment#support-in-ios-and-android-sdks) for more information.

## Local overrides

To locally override gates/configs/experiments/layers for testing, Statsig offers convenient methods for a quick local override. Unless you call the remove method, the SDK persists these session-to-session on the client's device. These overrides apply locally only and don't affect definitions in the console or elsewhere.

```kotlin
// Overrides the given gate to the specified value
overrideGate(gateName: String, value: Boolean)

// Overrides the given config (dynamic config or experiment) to the provided value
overrideConfig(configName: String, value: Map<String, Any>)

// Removes any overrides associated with the provided gate/config/experiment name
removeOverride(name: String)

// Removes all overrides
removeAllOverrides()

// Returns the set of gate and config overrides currently in place on the client
getAllOverrides(): StatsigOverrides

class StatsigOverrides(
    @SerializedName("gates")
    val gates: MutableMap<String, Boolean>,

    @SerializedName("configs")
    val configs: MutableMap<String, Map<String, Any>>
    ) {}
```

## Manual exposures

> **Warning:**
>
> Manual logging is error-prone and can introduce issues like uneven exposures, which compromise experiment results.

You can query your gates/experiments without triggering an exposure, and manually log the exposures later:

#### Check Gate

To check a gate without an exposure being logged:

#### Kotlin

```kotlin
val result = Statsig.checkGateWithExposureLoggingDisabled("a_gate_name")
```

#### Java

```java
boolean result = Statsig.checkGateWithExposureLoggingDisabled("a_gate_name");
```

Later, to manually log the gate exposure:

#### Kotlin

```kotlin
Statsig.manuallyLogGateExposure("a_gate_name")
```

#### Java

```java
Statsig.manuallyLogGateExposure("a_gate_name");
```

#### Get Config

To get a dynamic config without an exposure being logged:

#### Kotlin

```kotlin
val config = Statsig.getConfigWithExposureLoggingDisabled("a_config_name")
```

#### Java

```java
DynamicConfig config = Statsig.getConfigWithExposureLoggingDisabled("a_config_name");
```

Later, to manually log the config exposure:

#### Kotlin

```kotlin
Statsig.manuallyLogConfigExposure("a_config_name")
```

#### Java

```java
Statsig.manuallyLogConfigExposure("a_config_name");
```

#### Get Experiment

To get an experiment without an exposure being logged:

#### Kotlin

```kotlin
val experiment = Statsig.getExperimentWithExposureLoggingDisabled("an_experiment_name")
```

#### Java

```java
DynamicConfig experiment = Statsig.getExperimentWithExposureLoggingDisabled("an_experiment_name");
```

Later, to manually log the experiment exposure:

#### Kotlin

```kotlin
Statsig.manuallyLogExperimentExposure("an_experiment_name", false)
```

#### Java

```java
Statsig.manuallyLogExperimentExposure("an_experiment_name", false);
```

#### Get Layer

To get a layer parameter without an exposure being logged:

#### Kotlin

```kotlin
val layer = Statsig.getLayerWithExposureLoggingDisabled("a_layer_name", false)
val result = layer.getString("a_parameter_name", "fallback")
```

#### Java

```java
Layer layer = Statsig.getLayerWithExposureLoggingDisabled("a_layer_name");
String result = layer.getString("a_parameter_name", "fallback");
```

Later, to manually log the layer parameter exposure:

#### Kotlin

```kotlin
Statsig.manuallyLogLayerParameterExposure("a_layer_name", "a_parameter_name", false)
```

#### Java

```java
Statsig.manuallyLogLayerParameterExposure("a_layer_name", "a_parameter_name", false);
```

## StableID

Each client SDK has a stableID: a device-level identifier that the SDK generates the first time it initializes and stores locally for all future sessions. The stableID doesn't change unless you wipe storage or delete the app. The stableID enables device-level experiments and experiments where other user-identifiable information is unavailable, such as for logged-out users.

```kotlin
// Retrieve the StableID
Statsig.getStableID(); 

// Override the StableID before initializing, if you have something you'd prefer to use instead
val opts = StatsigOptions(overrideStableID = "my_stable_id")
Statsig.initialize(app, "client-xyx", options = opts)
```

## Using multiple instances of the SDK

The examples above use the SDK's singleton. The SDK also supports multiple instances. The `Statsig` singleton wraps a single instance of the SDK (typically called a `StatsigClient`) that you can instantiate directly.

> **Note:**
>
> You must use a different SDK key for each SDK instance you create. Various functionality of the Statsig client depends on the SDK key you use, so using the same key leads to collisions.

All top-level static methods from the singleton are available as instance methods. To create an instance of the Statsig SDK:

#### Java

```java
StatsigClient client = new StatsigClient();
client.initializeAsync(application, sdkKey, user, callback, options);
```

#### Kotlin

```kotlin
var client: StatsigClient = StatsigClient()
client.initialize(application, sdkKey, user, options)
```

## Initialize response

The SDK provides a method to access the raw values used internally for gate, config, and layer evaluation. This is useful for debugging or advanced use cases where you need to access the underlying data. For example, you can use these values to bootstrap another SDK, such as the JavaScript SDK when opening an in-app browser.

The `getInitializeResponseJson` method returns an `ExternalInitializeResponse` object that contains:

1. A JSON string representation of the initialize response values
2. Evaluation details that provide metadata about how the SDK obtained the values (network, cache, etc.)

#### Java

```java
// Get the raw values that the SDK is using internally to provide gate/config/layer results
ExternalInitializeResponse response = Statsig.getInitializeResponseJson();

// Get the JSON string representation of the initialize response
String jsonValues = response.getInitializeResponseJSON();

// Get the evaluation details
EvaluationDetails details = response.getEvaluationDetails();
```

#### Kotlin

```kotlin
// Get the raw values that the SDK is using internally to provide gate/config/layer results
val response = Statsig.getInitializeResponseJson()

// Get the JSON string representation of the initialize response
val jsonValues = response.getInitializeResponseJSON()

// Get the evaluation details
val details = response.getEvaluationDetails()
```

