# Android On Device Evaluation SDK

{% callout type="info" %}
Statsig recommends its normal (remote evaluation) SDKs for most client applications. Understand the use case and privacy risks by reading the [On-Device Eval SDK overview](https://docs.statsig.com/client/onDeviceOverview). On-device evaluation SDKs are for Enterprise & Pro Tier only.
{% /callout %}

These SDKs use a different paradigm than their precomputed counterparts ([JS](https://docs.statsig.com/client/javascript-sdk), [Android](https://docs.statsig.com/client/Android), [iOS](https://docs.statsig.com/client/iosClientSDK)). Rather than requiring a user upfront, you can check gates/configs/experiments for any set of user properties. You can do this because the SDK downloads a complete representation of your project and evaluates checks in real time.

### Pros

* No network request needed when changing user properties: check the gate/config/experiment locally
* Can bring your own CDN or synchronously initialize with a preloaded project definition
* Lower latency to download configs cached at the edge, rather than evaluated for a given user (which can't be cached as much)

### Cons

* The entire project definition lives client-side: your client key exposes the names and configurations of all experiments and feature flags. Refer to [client key with server permission best practices](https://docs.statsig.com/access-management/api-keys#client-keys-with-server-permissions).
* Payload size is strictly larger than what is required for the traditional SDKs
* Evaluation performance is slightly slower - rather than looking up the value, the SDK must actually evaluate targeting conditions and an allocation decision
* Doesn't support ID list segments with > 1000 IDs
* Doesn't support IP or User Agent based checks (Browser Version/Name, OS Version/Name, IP, Country)

## Set up the SDK

{% steps %}
{% step title="Install the SDK" %}
You can install the SDK using JitPack. Go to https://jitpack.io/#statsig-io/android-local-eval for the latest version and installation steps.
{% /step %}

{% step title="Initialize the SDK" %}
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 want to target later in a gate or experiment.

{% callout type="warning" %}
For On-Device Evaluation, you need to add the **"Allow Download Config Specs"** scope. Client keys can't download the project definition for on-device evaluation by default.

While client keys are safe to include, always keep Server and Console keys private.
{% /callout %}

{% accordion title="How to add the scope" %}
{% tabs %}
{% tab title="New SDK Keys" %}
When creating a new client key, select **"Allow Download Config Specs"**

![Add DCS Scope to New Key](https://docs.statsig.com/images/local-eval/new-keys.png)
{% /tab %}

{% tab title="Existing SDK Keys" %}
To add the scope to an existing key, under **Project Settings** → **API Keys** → **Client API Keys**, select **Actions** → **Edit Scopes**, and select **"Allow Download Config Specs"**, then **Save**.

![Add DCS Scope to Existing Key](https://docs.statsig.com/images/local-eval/existing-keys.png)
{% /tab %}
{% /tabs %}
{% /accordion %}

{% codetabs %}
```java Java
import com.statsig.androidlocalevalsdk.*;

// ...

android.app.Application app = // ref to your Application instance

StatsigOptions opts = new StatsigOptions();
opts.setEnvironmentParameter("tier", "staging");

StatsigClient client = Statsig.INSTANCE.getClient();
client.initializeAsync(
        app,
        "client-YOUR_CLIENT_SDK_KEY",
        new IStatsigCallback() {
            @Override
            public void onStatsigInitialize(@NotNull InitializationDetails initDetails) {
                // Statsig Ready
            }

            @Override
            public void onStatsigInitialize() {
                // deprecated
            }
        },
        opts
);

// or, create your own instance of StatsigClient
StatsigClient client = new StatsigClient();
client.initializeAsync(...);
```

```kotlin Kotlin
import com.statsig.androidlocalevalsdk.*

// ...

val opts = StatsigOptions()
opts.setEnvironmentParameter("tier", "staging")

Statsig.client.initializeAsync(
    application, // ref to your Application instance
    "client-YOUR_CLIENT_SDK_KEY",
    object : IStatsigCallback {
        override fun onStatsigInitialize(initDetails: InitializationDetails) {
            // Statsig Ready
        }

        override fun onStatsigInitialize() {
            // deprecated
        }
    },
    opts
)

// or, create your own instance of StatsigClient
val client = StatsigClient()
client.initializeAsync(...)
```
{% /codetabs %}

### Synchronous initialization

```kotlin
import com.statsig.androidlocalevalsdk.*

 // (optional) Configure the SDK if needed
val opts = StatsigOptions()
opts.environment.tier = "staging"

val specs = "..." // JSON string of your configurations

let details = Statsig.client.initializeSync(application, "client-YOUR_CLIENT_SDK_KEY", specs, opts)
```

You can configure the SDK to use cached values if they are newer than the local file.
This is useful if you ship your app with a local file but want to use it only for the first session.
In the following example, the SDK only uses initialSpecs if there is no cache or if the cache is older than initialSpecs.

```kotlin
val options = StatsigOptions()
options.useNewerCacheValuesOverProvidedValues = true

Statsig.client.initializeSync(
  application,
  "client-YOUR_CLIENT_SDK_KEY",
  specs,
  options
)
```

{% callout type="note" %}
You can get a copy of your current specs data by visiting: `https://api.statsigcdn.com/v1/download_config_specs/client-{YOUR_SDK_KEY}.json`
{% /callout %}
{% /step %}
{% /steps %}

## Working with the SDK

### Checking a Feature Flag/Gate

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

{% codetabs %}
```java Java
StatsigUser user = new StatsigUser("a-user");
StatsigClient client = Statsig.INSTANCE.getClient();

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

```kotlin Kotlin
val user = StatsigUser("user_id")

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

### Reading a Dynamic Config

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

{% codetabs %}
```java Java
StatsigUser user = new StatsigUser("a-user");
StatsigClient client = Statsig.INSTANCE.getClient();

DynamicConfig config = client.getConfig(user, "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 user = StatsigUser("user_id")
val config = Statsig.client.getConfig(user, "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 %}

### Getting a Layer/Experiment

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

{% codetabs %}
```java Java
StatsigUser user = new StatsigUser("a-user");
StatsigClient client = Statsig.INSTANCE.getClient();

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

// or, via getExperiment
DynamicConfig titleExperiment = client.getExperiment(user, "new_user_promo_title");
DynamicConfig priceExperiment = client.getExperiment(user, "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
val user = StatsigUser("user_id")

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

// or, via getExperiment
val titleExperiment = Statsig.client.getExperiment(user, "new_user_promo_title")
val priceExperiment = Statsig.client.getExperiment(user, "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 Experiment, you may want to track custom events to see how new features or different experiment groups affect those events. Call the Log Event API for the event. You can also provide a value and metadata object to log with the event:

{% codetabs %}
```java Java
StatsigUser user = new StatsigUser("user_id");
StatsigClient client = Statsig.INSTANCE.getClient();

client.logEvent(user, "purchase", 2.99, Map.of("item_name", "remove_ads"));
```

```kotlin Kotlin
val user = StatsigUser("user_id")
Statsig.client.logEvent(user, "purchase", 2.99, mapOf("item_name" to "remove_ads"))
```
{% /codetabs %}

### Code examples

You can find working sample apps in the repository:

* [Java & Kotlin Examples](https://github.com/statsig-io/android-local-eval/tree/main/samples)

## Statsig User

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

Most of the time, you need the `userID` field to provide a consistent experience for a given
user (refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) to understand how to correctly run experiments for logged-out
users).

Besides `userID`, Statsig also supports `email`, `ip`, `userAgent`, `country`, `locale` and `appVersion` as top-level fields on
StatsigUser. In addition, you can pass any key-value pairs in an object/dictionary to the `custom` field and 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:

{% callout type="note" %}
For the Android On-Device Evaluation SDK, you pass the `StatsigUser` object directly into each evaluation method (`checkGate`, `getConfig`, etc.) rather than during initialization.
{% /callout %}

{% callout type="note" %}
Unlike precomputed evaluation SDKs, the on-device evaluation SDK doesn't have an `updateUser` method since it evaluates gates/configs/experiments in real-time for any user object you pass in.
{% /callout %}

### Setting a global user

To avoid passing the user object to every evaluation call, set a global user. When checking a gate/experiment/layer, provide `null` for the user to use the global user. The SDK uses the global user for all evaluations unless you provide a specific user.

```kotlin
Statsig.client.setGlobalUser(myGlobalUser)

Statsig.client.checkGate(null, "my_gate") // <- Will use myGlobalUser
Statsig.client.checkGate(StatsigUser(userID: "user-123"), "my_gate") // <- Will NOT use myGlobalUser
```

## Statsig Options

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

{% parameter name="configSpecAPI" type="String" %}
The endpoint to use for downloading config spec network requests. You shouldn't need to override this (unless you have another API that implements the Statsig API endpoints).
{% /parameter %}

{% parameter name="eventLoggingAPI" type="String" %}
The endpoint to use for log events. You shouldn't need to override this (unless you have another API that implements the Statsig API endpoints).
{% /parameter %}

{% parameter name="initTimeoutMs" type="Long" %}
Milliseconds to wait for the initial network request before calling the completion block. The Statsig client returns either cached values (if any) or default values if you call checkGate/getConfig/getExperiment before the initial network request completes. Set to `0` to wait indefinitely for the latest values.
{% /parameter %}

{% parameter name="overrideStableID" type="String?" %}
Overrides the `stableID` in the SDK set for the user.
{% /parameter %}

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

{% parameter name="initializeValues" type="Map<String, Any>?" %}
Provide the `download_config_specs` response values directly to the Android SDK to synchronously initialize the client. You can get a copy of your current specs data by visiting: `https://api.statsigcdn.com/v1/download_config_specs/client-{YOUR_SDK_KEY}.json`
{% /parameter %}

{% parameter name="disableDiagnosticsLogging" type="Boolean" %}
Prevent the SDK from sending useful debug information to Statsig.
{% /parameter %}

#### Methods

* **setTier | setEnvironmentParameter | getEnvironment**
  * Signals the environment tier for the user.
  * `setTier` can be PRODUCTION, STAGING or DEVELOPMENT. For example, passing `Tier.STAGING` allows your users to pass any condition set for the staging environment tier. Conditions set only for other environment tiers fail.
  * Use `setEnvironmentParameter` for custom tiers, eg `options.setEnvironmentParameter("tier", "test")`

## Lifecycle & advanced usage

## Shutting Statsig down

The SDK keeps event logs in client cache and flushes them periodically to save data and battery usage. Because the SDK flushes only periodically, it may not have flushed some events when your app shuts down.

To ensure the SDK flushes or saves all logged events locally, shut down Statsig when your app is closing:

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

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

## Post init syncing

### From network

By default, the SDK syncs only during initialization. To re-sync after initialization, call the `Statsig.client.updateAsync` method. This triggers a network call to fetch the latest changes from the server.

```kotlin
val details = Statsig.client.updateAsync()
```

### Scheduled polling

To have the SDK regularly poll for updates, start the polling task with `Statsig.client.scheduleBackgroundUpdates()`. The SDK fetches the latest changes from the network on each interval.

```kotlin
val pollingTask = Statsig.cloent.scheduleBackgroundUpdates() // Defaults to 1 hour interval

// or, specify a custom interval
val intervalSeconds = 300
val pollingTask = Statsig.client.scheduleBackgroundUpdates(intervalSeconds)

// and, if you need to cancel it later
pollingTask?.cancel()
```

## Using persistent evaluations

To ensure that a user's variant stays consistent while an experiment is running, regardless of changes to allocation or targeting, implement the `UserPersistentStorageInterface` and set it in `StatsigOptions` when you initialize the SDK.

#### Synchronous persistent evaluations

The `UserPersistentStorageInterface` exposes two methods for synchronous persistent storage, which the SDK calls by default when evaluating an experiment.

```
interface UserPersistentStorageInterface {
    suspend fun load(key: String): PersistedValues
    fun save(key: String, experimentName: String, data: String)
    fun delete(key: String, experiment: String)
    ...
}
```

The `key` string is a combination of ID and ID Type: for example, `"123:userID"` or `"abc:stableID"`. The SDK constructs this key and calls `get` and `set` on it by default.

Use this interface to persist evaluations synchronously to local storage. If you need an async interface, refer to Asynchronous persistent evaluations.

#### Asynchronous persistent evaluations

The `UserPersistentStorageInterface` exposes two methods for asynchronous persistent evaluations. Because the `getExperiment` call is synchronous, you must load the value first and pass it in as `userPersistedValues`.

```kotlin
interface UserPersistentStorageInterface {
    fun loadAsync(key: String, callback: IPersistentStorageCallback)
    fun save(key: String, experimentName: String, data: String)
    fun delete(key: String, experiment: String)
    ...
}
interface IPersistentStorageCallback {
    fun onLoaded(values: PersistedValues)
}
```

The SDK offers a top-level method to load the value for a given user and ID Type:

```kotlin
// Asynchronous load values
val userPersistedValues = Statsig.client.loadUserPersistedValuesAsync(
  user: StatsigUser,
  idType: string, // userID, stableID, customIDxyz, etc
  callback: IPersistentStorageCallback
);

// Synchronous load values 
val userPersistedvalues = Statsig.client.loadUserPersistedValues(
    user: StatsigUser,
  idType: string, // userID, stableID, customIDxyz, etc
)
```

After implementing the `UserPersistentStorageInterface` and setting it on `StatsigOptions`, the call site looks like this:

```kotlin
// Asynchronous 
val callback = object: IPersistentStorageCallback {
    @override
    fun onLoaded(values: PersistedValues) {
        Statsig.getExperiment(user, "sample_experiment", GetExperimentOptions(userPersistedValues = values))
    }
}
val userValues = Statsig.client.loadUserPersistedValuesAsync(user, "userID", callback)

// Synchronous
val user = StatsigUser(userID = "user123")
val userValues = Statsig.client.loadUserPersistedValues(user, 'userID');
const experiment = statsig.getExperiment({userID: "123"}, 'the_allocated_experiment', { userPersistedValues: userValues });
```

If you're using Java, override only the `loadAsync` function and leave the `load` function empty.

## Local overrides

You can override the values the Statsig SDK returns. This is useful in unit testing or for enabling features for local development.

To set up local overrides, pass an instance of `LocalOverrideAdapter` to the SDK through the `StatsigOptions` object.

{% callout type="note" %}
You can write your own override adapter. You can implement the [`IOverrideAdapter`](https://github.com/statsig-io/android-local-eval/blob/main/src/main/java/com/statsig/androidlocalevalsdk/IOverrideAdapter.kt) interface and pass that in instead.
{% /callout %}

{% codetabs %}
```kotlin Kotlin
val user = StatsigUser("user-a")

val overrides = LocalOverrideAdapter()

// Override a gate
overrides.setGate(user, "local_override_gate", true)

// Override a dynamic config (Similar for Layer and Experiment)
val config = DynamicConfig("local_override_dynamic_config", mapOf("key" to "val"))
overrides.setConfig(user, config)

val opts = StatsigOptions()
opts.overrideAdapter = overrides

Statsig.client.initializeAsync(
  app, 
  YOUR_SDK_KEY, 
  callback, 
  opts // <- Pass in StatsigOptions
)
```

```java Java
StatsigUser user = new StatsigUser("a-user");

LocalOverrideAdapter overrides = new LocalOverrideAdapter();

// Override a gate
overrides.setGate(user, "local_override_gate", true);

// Override a dynamic config (Similar for Layer and Experiment)
HashMap<String, Object> configValue = new HashMap<String, Object>() {};
DynamicConfig config = new DynamicConfig(
  "local_override_dynamic_config",
  configValue,
  "local_override",
  null,
  new ArrayList<Map<String, String>>(),
  null
);
overrides.setConfig(user, config);

StatsigOptions opts = new StatsigOptions();
opts.setOverrideAdapter(overrides);

StatsigClient client = Statsig.INSTANCE.getClient();
client.initializeAsync(
  app,
  YOUR_SDK_KEY,
  callback,
  opts // <- Pass in StatsigOptions
);
```
{% /codetabs %}

## FAQs



{% accordion-group %}
{% accordion title="How do I run experiments for logged out users?" %}
Refer to [Device-level experiments](https://docs.statsig.com/guides/first-device-level-experiment).
{% /accordion %}
{% /accordion-group %}

## Additional resources

* [On-Device Evaluation SDK Overview](https://docs.statsig.com/client/onDeviceOverview)
* [Client Keys with Server Permissions](https://docs.statsig.com/access-management/api-keys#client-keys-with-server-permissions)
* [Debugging SDK Evaluations](https://docs.statsig.com/sdks/debugging)
