Skip to main content

Setup the SDK

1

Install the SDK

v4.37.1 and higher are published to only Maven Central. To install the SDK, set the Maven Central repository in your build.gradle.
dependencies {
    implementation "com.statsig:android-sdk:4.37.1"
}
Legacy versions (<=V4.37.0) can be installed with Jitpack.
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.
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
    }

}

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

Reading a Dynamic Config

Feature Gates can be very useful for simple on/off switches, with optional but advanced user targeting. However, if you want to be able send a different set of values (strings, numbers, and etc.) to your clients based on specific user attributes, e.g. country, Dynamic Configs can help you with that. The API is very similar to Feature Gates, but you get an entire json object you can configure on the server and you can fetch typed parameters from it. For example:
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

Then we have Layers/Experiments, which you can use to run A/B/n experiments. We offer two APIs, but we recommend the use of layers to enable quicker iterations with parameter reuse.
// 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);

Logging an Event

Now that you have a Feature Gate or an Experiment set up, you may want to track some custom events and see how your new features or different experiment groups affect these events. This is super easy with Statsig - simply call the Log Event API for the event, and you can additionally provide some value and/or an object of metadata to be logged together with the event:
Statsig.logEvent("purchase", 2.99, Map.of("item_name", "remove_ads"));

Parameter Stores

Parameter Stores hold a set of parameters for your mobile app. These parameters can be remapped on-the-fly from a static value to a Statsig entity (Feature Gates, Experiments, and Layers), so you can decouple your code from the configuration in Statsig. Read more about Param Stores here.

Getting a Parameter Store

To fetch a set of parameters, use the following api:
ParameterStore homepageStore = Statsig.getParameterStore("homepage");

Getting a parameter

You can then access parameters like this:
String title = homepageStore.getString(
    "title", //parameter name
    "Welcome" // default value
);

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

Statsig User

You need to provide a StatsigUser object to check/get your configurations. You should pass as much information as possible in order to take advantage of advanced gate and config conditions. Most of the time, the userID field is needed in order to provide a consistent experience for a given user (see logged-out experiments to understand how to correctly run experiments for logged-out users). Besides userID, we also have 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 be able to create targeting based on them. Once the user logs in or has an update/changed, make sure to call updateUser with the updated userID and/or any other updated user attributes:
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
}

Private Attributes

Have sensitive user PII data that should not be logged? No problem, we have a solution for it! On the StatsigUser object we also have a field called privateAttributes, which is a simple object/dictionary that you can use to set private user attributes. Any attribute set in privateAttributes will only be used for evaluation/targeting, and removed from any logs before they are sent to Statsig server. For example, if you have feature gates that should only pass for users with emails ending in “@statsig.com”, but do not want to log your users’ email addresses to Statsig, you can simply add the key-value pair { email: "my_user@statsig.com" } to privateAttributes on the user and that’s it!

Statsig Options

You can pass in an optional parameter options in addition to sdkKey and user during initialization to customize the Statsig client.
api
String
default:"https://api.statsig.com/v1/"
Default endpoint for all SDK network requests. Do not override unless you implement the Statsig API elsewhere.
disableCurrentActivityLogging
Boolean
default:"false"
Include the current top-level activity on logged events by default. Set to true to disable.
disableDiagnosticsLogging
Boolean
default:"false"
deprecated
deprecated
Deprecated. Previously prevented the SDK from sending diagnostic information.
initTimeoutMs
Long
default:"3000"
Milliseconds to wait for the initial request before completing. Set to 0 to wait indefinitely.
enableAutoValueUpdate
Boolean
default:"false"
Periodically fetch updated values for the current user when enabled.
autoValueUpdateIntervalMinutes
Double
default:"1.0"
Frequency (in minutes) for auto value refresh. Minimum is 1 minute.
overrideStableID
String?
default:"null"
Override the SDK-generated stableID for the user.
loadCacheAsync
Boolean
default:"false"
Whether the SDK should block on loading saved values from disk.
initializeValues
Map<String, Any>?
default:"null"
Provide the initialize response directly to bootstrap the client synchronously. See NodeJS Server SDK for generating values and the Bootstrap docs.
disableHashing
Boolean?
default:"false"
When true, gate/config/experiment names are not hashed and remain readable. Requires special authorization from Statsig.
customCacheKey
((sdkKey: String, user: StatsigUser) -> String)
Override how the cache key is generated for stored values when the default does not fit your needs.
evaluationCallback
((config: BaseConfig) -> Unit)
Callback invoked whenever a gate, config, experiment, or layer is checked. Receives the evaluated BaseConfig.

Methods

  • setTier | setEnvironmentParameter | getEnvironment
    • used to signal the environment tier the user is currently in.
    • 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")

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 will prevent the Statsig client from sending logging events over the network or saving events to its on-disk cache. The 1000 most recent events will be queued in memory. They can be logged to network (or cached) if loggingEnabled is set to true later during that session.
    • Calling Statsig.flush() after setting loggingEnabled to true will immediately clear the queue and minimize loss of older log events
    • This can be useful for cases where it is necessary for users to grant permission before events should be logged, or in any other cases where logging should not be enabled

Shutting Statsig Down

In order to save users’ data and battery usage, as well as prevent logged events from being dropped, we keep event logs in client cache and flush periodically. Because of this, some events may not have been sent when your app shuts down. To make sure all logged events are properly flushed or saved locally, you should tell Statsig to shutdown when your app is closing:
Statsig.shutdown();

Using Persistent Evaluations

If you want to ensure that a user’s variant stays consistent while an experiment is running, regardless of changes to allocation or targeting, you can use persistent storage. The Android SDK supports a minimal implementation using the keepDeviceValues flag, see the Client Persistent Assignment Doc for more info.

Local Overrides

If you want to locally override gates/configs/experiments/layers for testing, Statsig offers convenient methods for a quick local override. Unless you call the remove method, these will be persisted session-to-session on the client’s device. Note that these overrides only apply locally - they don’t impact definitions in the console or elsewhere.
// 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

Manual logging is error-prone and can often 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
  • Get Config
  • Get Experiment
  • Get Layer
To check a gate without an exposure being logged:
val result = Statsig.checkGateWithExposureLoggingDisabled("a_gate_name")
Later, to manually log the gate exposure:
Statsig.manuallyLogGateExposure("a_gate_name")

StableID

Each client SDK has the notion of stableID, a devive-level identifier that is generated the first time the SDK is initialized and is stored locally for all future sessions. Unless storage is wiped (or app deleted), the stableID will not change. This allows us to run device level experiments and experiments when other user identifiable information is unavailable (Logged out users).
// 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

Up to this point, we’ve used the SDK’s singleton. We also support creating multiples instances of the SDK - the Statsig singleton wraps a single instance of the SDK (typically called a StatsigClient) that you can instantiate.
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 will lead to collisions.
All top level static methods from the singleton carry over as instance methods. To create an instance of the Statsig sdk:
StatsigClient client = new StatsigClient();
client.initializeAsync(application, sdkKey, user, callback, options);

Initialize Response

The SDK provides a method to access the raw values that are used internally for gate, config, and layer value. This can be useful for debugging or for advanced use cases where you need to access the underlying data. For example, you can use these values to bootstrap another SDK, like the javascript SDK when you open 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.)
// 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();
I