Source code: statsig-io/android-sdk
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.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
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 (thinkreturn false;
) by default.
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: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.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: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:Getting a parameter
You can then access parameters like this: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, theuserID
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:
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 calledprivateAttributes
, 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 parameteroptions
in addition to sdkKey
and user
during initialization to customize the Statsig client.
Default endpoint for all SDK network requests. Do not override unless you implement the Statsig API elsewhere.
Include the current top-level activity on logged events by default. Set to
true
to disable.Deprecated. Previously prevented the SDK from sending diagnostic information.
Milliseconds to wait for the initial request before completing. Set to
0
to wait indefinitely.Periodically fetch updated values for the current user when enabled.
Frequency (in minutes) for auto value refresh. Minimum is
1
minute.Override the SDK-generated
stableID
for the user.Whether the SDK should block on loading saved values from disk.
Provide the initialize response directly to bootstrap the client synchronously. See NodeJS Server SDK for generating values and the Bootstrap docs.
When
true
, gate/config/experiment names are not hashed and remain readable. Requires special authorization from Statsig.Override how the cache key is generated for stored values when the default does not fit your needs.
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 ofTier.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, egoptions.setEnvironmentParameter("tier", "test")
Runtime Options
Starting inV4.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
, defaulttrue
- 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) ifloggingEnabled
is set totrue
later during that session. - Calling
Statsig.flush()
after settingloggingEnabled
totrue
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
- Setting this value to
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: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.Manual Exposures
Manual logging is error-prone and can often introduce issues like uneven exposures, which compromise experiment results.
- Check Gate
- Get Config
- Get Experiment
- Get Layer
To check a gate without an exposure being logged:Later, to manually log the gate exposure:
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).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 - theStatsig
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.
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. ThegetInitializeResponseJson
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.)