
## Set up the SDK

{% steps %}
{% step title="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).
{% /step %}

{% step title="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 on in a gate or experiment.

{% codetabs %}
```java MainActivity.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
    }

}
```

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

...

async {
    Statsig.initialize(
        this.application,
        "my_client_sdk_key",
        StatsigUser("user_id"),
    )
}.await()
```
{% /codetabs %}
{% /step %}
{% /steps %}

## Use the SDK

### Checking a Feature Flag/Gate

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

{% codetabs %}
```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)
```
{% /codetabs %}

### 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:

{% codetabs %}
```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
}
```
{% /codetabs %}

### Getting a Layer/Experiment

**Layers/Experiments** support running A/B/n experiments. Two APIs are available, but [layers](/experiments/layers-overview) are recommended to enable quicker iterations with parameter reuse.

{% codetabs %}
```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);
```
{% /codetabs %}

### 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 be logged with the event:

{% codetabs %}
```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"))
```
{% /codetabs %}

## 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), so you can decouple your code from the configuration in Statsig. Refer to [Param Stores](/client/concepts/parameter-stores) for more information.

### Getting a parameter store

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

{% codetabs %}
```java Java
ParameterStore homepageStore = Statsig.getParameterStore("homepage");
```

```kotlin Kotlin
val homepageStore = Statsig.getParameterStore("homepage")
```
{% /codetabs %}

### Getting a parameter

You can then access parameters like this:

{% codetabs %}
```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)
```
{% /codetabs %}

## 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](/guides/first-device-level-experiment) for how to run experiments for logged-out users).

In addition to `userID`, the following top-level fields are available on StatsigUser: `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:

{% codetabs %}
```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"))
```
{% /codetabs %}

### Private attributes

To prevent sensitive user PII from being logged, 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, if you have feature gates that should only pass for users with emails ending in "@statsig.com" but don't want to log email addresses to Statsig, 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.

{% parameter name="api" type="String" %}
Default endpoint for all SDK network requests. Do not override unless you implement the Statsig API elsewhere.
{% /parameter %}

{% parameter name="disableCurrentActivityLogging" type="Boolean" %}
Include the current top-level activity on logged events by default. Set to `true` to disable.
{% /parameter %}

{% parameter name="disableDiagnosticsLogging" type="Boolean" %}
Deprecated. Previously prevented the SDK from sending diagnostic information.
{% /parameter %}

{% parameter name="initTimeoutMs" type="Long" %}
Milliseconds to wait for the initial request before completing. Set to `0` to wait indefinitely.
{% /parameter %}

{% parameter name="enableAutoValueUpdate" type="Boolean" %}
Periodically fetch updated values for the current user when enabled.
{% /parameter %}

{% parameter name="autoValueUpdateIntervalMinutes" type="Double" %}
Frequency (in minutes) for auto value refresh. Minimum is `1` minute.
{% /parameter %}

{% parameter name="overrideStableID" type="String?" %}
Override the SDK-generated `stableID` for the user.
{% /parameter %}

{% parameter name="loadCacheAsync" type="Boolean" %}
Whether the SDK should block on loading saved values from disk.
{% /parameter %}

{% parameter name="initializeValues" type="Map<String, Any>?" %}
Provide the initialize response directly to bootstrap the client synchronously. Go to the NodeJS Server SDK for generating values and the Bootstrap docs.
{% /parameter %}

{% parameter name="disableHashing" type="Boolean?" %}
When `true`, gate/config/experiment names aren't hashed and remain readable. Requires special authorization from Statsig.
{% /parameter %}

{% parameter name="customCacheKey" type="((sdkKey: String, user: StatsigUser) -> String)" %}
Override how the cache key is generated for stored values when the default doesn't fit your needs.
{% /parameter %}

{% parameter name="evaluationCallback" type="((config: BaseConfig) -> Unit)" %}
Callback invoked whenever a gate, config, experiment, or layer is checked. Receives the evaluated `BaseConfig`.
{% /parameter %}

{% parameter name="lifetimeCallback" type="IStatsigLifetimeCallback?" %}
Callbacks that may trigger multiple times over the lifetime of the client SDK.
The SDK calls them on the main thread.

* `onValuesUpdated()` - called whenever the fired when new values are received and available for use. May be called after `Statsig.updateUser()`, `Statsig.updateUserAsync()`, or auto value updates (see `enableAutoValueUpdate` above)
{% /parameter %}

#### Methods

* **setTier | setEnvironmentParameter | getEnvironment**
  * used to signal the environment tier the user is currently in.
  * `setTier` can be PRODUCTION, STAGING or DEVELOPMENT. For example, passing in a value of `Tier.STAGING` allows your users to pass any condition that passes for the staging environment tier, and fail any condition that only passes for other environment tiers.
  * `setEnvironmentParameter` can be used for custom tiers, for example `options.setEnvironmentParameter("tier", "test")`

#### Runtime options

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

These options are defined in `StatsigRuntimeMutableOptions` (which `StatsigOptions` extends) and are detailed below.

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 1000 most recent events are queued 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 events should be logged, or in any other cases where logging shouldn't be enabled.

## Shutting Statsig Down

To save data and battery usage and prevent logged events from being dropped, the SDK keeps event logs in client cache and flushes them periodically. Because of this, some events may not have been sent when your app shuts down.

To ensure all logged events are flushed or saved locally, call `shutdown` when your app is closing:

{% codetabs %}
```java Java
Statsig.shutdown();
```

```kotlin Kotlin
Statsig.shutdown()
```
{% /codetabs %}

## 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](/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

{% callout type="warning" %}
Manual logging is error-prone and can introduce issues like uneven exposures, which compromise experiment results.
{% /callout %}

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

{% tabs %}
{% tab title="Check Gate" %}
To check a gate without an exposure being logged:

{% codetabs %}
```kotlin Kotlin
val result = Statsig.checkGateWithExposureLoggingDisabled("a_gate_name")
```

```java Java
boolean result = Statsig.checkGateWithExposureLoggingDisabled("a_gate_name");
```
{% /codetabs %}

Later, to manually log the gate exposure:

{% codetabs %}
```kotlin Kotlin
Statsig.manuallyLogGateExposure("a_gate_name")
```

```java Java
Statsig.manuallyLogGateExposure("a_gate_name");
```
{% /codetabs %}
{% /tab %}

{% tab title="Get Config" %}
To get a dynamic config without an exposure being logged:

{% codetabs %}
```kotlin Kotlin
val config = Statsig.getConfigWithExposureLoggingDisabled("a_config_name")
```

```java Java
DynamicConfig config = Statsig.getConfigWithExposureLoggingDisabled("a_config_name");
```
{% /codetabs %}

Later, to manually log the config exposure:

{% codetabs %}
```kotlin Kotlin
Statsig.manuallyLogConfigExposure("a_config_name")
```

```java Java
Statsig.manuallyLogConfigExposure("a_config_name");
```
{% /codetabs %}
{% /tab %}

{% tab title="Get Experiment" %}
To get an experiment without an exposure being logged:

{% codetabs %}
```kotlin Kotlin
val experiment = Statsig.getExperimentWithExposureLoggingDisabled("an_experiment_name")
```

```java Java
DynamicConfig experiment = Statsig.getExperimentWithExposureLoggingDisabled("an_experiment_name");
```
{% /codetabs %}

Later, to manually log the experiment exposure:

{% codetabs %}
```kotlin Kotlin
Statsig.manuallyLogExperimentExposure("an_experiment_name", false)
```

```java Java
Statsig.manuallyLogExperimentExposure("an_experiment_name", false);
```
{% /codetabs %}
{% /tab %}

{% tab title="Get Layer" %}
To get a layer parameter without an exposure being logged:

{% codetabs %}
```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");
```
{% /codetabs %}

Later, to manually log the layer parameter exposure:

{% codetabs %}
```kotlin Kotlin
Statsig.manuallyLogLayerParameterExposure("a_layer_name", "a_parameter_name", false)
```

```java Java
Statsig.manuallyLogLayerParameterExposure("a_layer_name", "a_parameter_name", false);
```
{% /codetabs %}
{% /tab %}
{% /tabs %}

## StableID

Each client SDK has a stableID: a device-level identifier generated the first time the SDK is initialized and stored locally for all future sessions. The stableID doesn't change unless storage is wiped or the app is deleted. This 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. Multiple instances of the SDK are also supported. The `Statsig` singleton wraps a single instance of the SDK (typically called a `StatsigClient`) that you can instantiate directly.

{% callout type="note" %}
You must use a different SDK key for each SDK instance you create for this to work. Various functionality of the Statsig client is keyed on the SDK key being used. Using the same key leads to collisions.
{% /callout %}

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

{% codetabs %}
```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)
```
{% /codetabs %}

## 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 values were obtained (network, cache, etc.)

{% codetabs %}
```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()
```
{% /codetabs %}
