You can install legacy versions (<=V4.37.0) with Jitpack.
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.
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
After the SDK is initialized, check a Feature Gate. 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.
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 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:
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. Two APIs are available, but layers are recommended to enable quicker iterations with parameter reuse.
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:
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 for more information.
Getting a parameter store
To fetch a set of parameters, use the following API:
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 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 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:
StatsigUser newUser = new StatsigUser("new_user_id");Statsig.updateUserAsync(newUser, this); // this must implement IStatsigCallback...@Overridepublic void onStatsigUpdateUser() { // User has been updated and values have been refetched for the new user}
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.
apiString
Default endpoint for all SDK network requests. Do not override unless you implement the Statsig API elsewhere.
disableCurrentActivityLoggingBoolean
Include the current top-level activity on logged events by default. Set to true to disable.
disableDiagnosticsLoggingBoolean
Deprecated. Previously prevented the SDK from sending diagnostic information.
initTimeoutMsLong
Milliseconds to wait for the initial request before completing. Set to 0 to wait indefinitely.
enableAutoValueUpdateBoolean
Periodically fetch updated values for the current user when enabled.
autoValueUpdateIntervalMinutesDouble
Frequency (in minutes) for auto value refresh. Minimum is 1 minute.
overrideStableIDString?
Override the SDK-generated stableID for the user.
loadCacheAsyncBoolean
Whether the SDK should block on loading saved values from disk.
initializeValuesMap<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.
disableHashingBoolean?
When true, gate/config/experiment names aren't hashed and remain readable. Requires special authorization from Statsig.
Override how the cache key is generated for stored values when the default doesn't fit your needs.
evaluationCallback((config: BaseConfig) -> Unit)
Callback invoked whenever a gate, config, experiment, or layer is checked. Receives the evaluated BaseConfig.
lifetimeCallbackIStatsigLifetimeCallback?
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)
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:
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 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 valueoverrideGate(gateName: String, value: Boolean)// Overrides the given config (dynamic config or experiment) to the provided valueoverrideConfig(configName: String, value: Map<String, Any>)// Removes any overrides associated with the provided gate/config/experiment nameremoveOverride(name: String)// Removes all overridesremoveAllOverrides()// Returns the set of gate and config overrides currently in place on the clientgetAllOverrides(): StatsigOverridesclass 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 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:
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 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 StableIDStatsig.getStableID(); // Override the StableID before initializing, if you have something you'd prefer to use insteadval 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.
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.
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 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:
A JSON string representation of the initialize response values
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 resultsExternalInitializeResponse response = Statsig.getInitializeResponseJson();// Get the JSON string representation of the initialize responseString jsonValues = response.getInitializeResponseJSON();// Get the evaluation detailsEvaluationDetails details = response.getEvaluationDetails();