On this page

Android On Device Evaluation SDK

Statsig's Android SDK for on-device evaluation.

Statsig's normal (remote evaluation) SDKs are recommended for most client applications. Understand the use case and privacy risks by reading the On-Device Eval SDK overview. On-device evaluation SDKs are for Enterprise & Pro Tier only.
These SDKs use a different paradigm than their precomputed counterparts (JS, Android, iOS). Rather than requiring a user upfront, you can check gates/configs/experiments for any set of user properties, 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 is available 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.
  • 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
  • Does not support ID list segments with > 1000 IDs
  • Does not support IP or User Agent based checks (Browser Version/Name, OS Version/Name, IP, Country)

Set Up the SDK

  1. 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.

  2. Initialize the SDK

    Next, initialize the SDK with a client SDK key from the "API Keys" tab on the Statsig console. These keys are safe to embed in a client application.Along with the key, pass in a User Object with the attributes you'd like to target later on in a gate or experiment.

    For On-Device Evaluation, you'll 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, Server and Console keys should always be kept private.

    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(...);
    

    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 it to only be used 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
    )
    

    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

Working with the SDK

Checking a Feature Flag/Gate

Now that your SDK is initialized, let's check a Feature Gate. Feature Gates can be used to create logic branches in code that can be rolled out to different users from the Statsig Console. Gates are always CLOSED or OFF (think return false;) by default.
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
}

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:

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);

Getting a Layer/Experiment

Layers/Experiments let you run A/B/n experiments. Two APIs are available, but Statsig recommends layers for quicker iterations with parameter reuse.
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);

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

StatsigUser user = new StatsigUser("user_id");
StatsigClient client = Statsig.INSTANCE.getClient();

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

Code Examples

Working sample apps are available in the repository:

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, the userID field is needed to provide a consistent experience for a given user (refer to logged-out experiments 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:

For the Android On-Device Evaluation SDK, you pass the StatsigUser object directly into each evaluation method (checkGate, getConfig, etc.) rather than during initialization.

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.

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 global user is used for all evaluations unless a specific user is provided.

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.

configSpecAPIString

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).

eventLoggingAPIString

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).

initTimeoutMsLong

Milliseconds to wait for the initial network request before calling the completion block. The Statsig client will return either cached values (if any) or default values if checkGate/getConfig/getExperiment is called before the initial network request completes. Set to 0 to wait indefinitely for the latest values.

overrideStableIDString?

Overrides the stableID in the SDK that is set for the user.

loadCacheAsyncBoolean

Whether or not the SDK should block on loading saved values from disk.

initializeValuesMap<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

disableDiagnosticsLoggingBoolean

Prevent the SDK from sending useful debug information to Statsig.

Methods

  • setTier | setEnvironmentParameter | getEnvironment
    • Used to signal the environment tier for the user.
    • setTier can be PRODUCTION, STAGING or DEVELOPMENT. e.g. passing in a value of Tier.STAGING will allow your users to pass any condition that pass for the staging environment tier, and fail any condition that only passes for other environment tiers.
    • setEnvironmentParameter can be used 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 of this, some events may not have been flushed when your app shuts down.

To ensure all logged events are flushed or saved locally, shut down Statsig when your app is closing:

Statsig.shutdown();

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 are called by default when evaluating an experiment.

plaintext
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, continue to the next section.

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)
}

A top-level method is available 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 are using Java, override only the loadAsync function and leave the load function empty.

Local Overrides

You can override the values returned by the Statsig SDK. 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.

It is possible to write your own override adapter. You can implement the IOverrideAdapter interface and pass that in instead.
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
)

FAQs

Additional Resources

Was this helpful?