This guide provides detailed information about our Android SDK. All of our SDKs are open source. Go to our Android SDK GitHub repository to see the source code.
Language Support
This library is compatible with Android SDK versions 15 and later (4.0.3 Ice Cream Sandwich).
Initialization
To get started, set up Split in your code base with two simple steps.
1. Import the SDK into your project
You can import the SDK into your project using any of the two methods defined below.
implementation 'io.split.client:android-client:2.6.9'
2. Instantiate the SDK and create a new Split client
The first time that the SDK is instantiated, it kicks off background tasks to update an in-memory cache and in-storage cache with small amounts of data fetched from Split servers. This process can take up to a few hundred milliseconds depending on the size of the data.
If the SDK is asked to evaluate which treatment to show to a customer for a specific split while it is in this intermediate state, it may not have the data necessary to run the evaluation. In this circumstance, the SDK does not fail, rather, it returns the control treatment.
After the first initialization, the fetched data is stored. Further initializations fetch data from that cache and the configuration is available immediately.
We recommend instantiating the SDK once as a singleton and reusing it throughout your application.
Include the API key for the environment that you are setting up the SDK for. The API key is available on your Organization Settings page, on the APIs tab. Choose "browser" type. This is a special type of API token with limited privileges to be used for the untrustable world of browsers or mobile clients. Learn more about API keys.
import io.split.android.client.SplitClient;
import io.split.android.client.SplitClientConfig;
import io.split.android.client.SplitFactory;
import io.split.android.client.SplitFactoryBuilder;
import io.split.android.client.api.Key;
//API Key
String apikey = "YOUR_API_KEY";
// Build SDK configuration by default
SplitClientConfig config = SplitClientConfig.builder()
.build();
// Create a new user key to be evaluated
String matchingKey = "key";
Key k = new Key(matchingKey);
// Create factory
SplitFactory splitFactory = SplitFactoryBuilder.build(apikey, k, config, getApplicationContext());
// Get Split Client instance
SplitClient client = splitFactory.client();
Using the SDK
Basic usage
To make sure the SDK is properly loaded before asking it for a treatment you should wait until the SDK is ready as shown below. We set the client to listen for the sdkReady
event triggered by the SDK before asking for an evaluation.
Once the sdkReady
event fires, you can use the getTreatment method to return the proper treatment based on the SPLIT_NAME you pass and the key you passed when instantiating the SDK.
From there, you simply need to use an if-else-if block as shown below and plug the code in for the different treatments that you defined in the Split UI. Make sure to remember the final else branch in your code to handle the client returning control.
client.on(SplitEvent.SDK_READY, new SplitEventTask() {
String treatment = client.getTreatment("SPLIT_NAME");
if (treatment.equals("on")) {
// insert code here to show on treatment
} else if (treatment.equals("off")) {
// insert code here to show off treatment
} else {
// insert your control treatment code here
}
});
client.on(SplitEvent.SDK_READY_TIMED_OUT, new SplitEventTask() {
// handle for timeouts here
}
Also, a sdkReadyFromCache
event is available, which allows to be aware of when the SDK has loaded data from cache. This way it is ready to evaluate splits using those locally cached definitions.
client.on(SplitEvent.SDK_READY_FROM_CACHE, new SplitEventTask() {
String treatment = client.getTreatment("SPLIT_NAME");
if (treatment.equals("on")) {
// insert code here to show on treatment
} else if (treatment.equals("off")) {
// insert code here to show off treatment
} else {
// insert your control treatment code here
}
});
Shutdown
Before letting your app shut down, call destroy()
as it gracefully shuts down the Split SDK by stopping all background threads, clearing caches, closing connections, and flushing the remaining unpublished impressions. Executing the client.destroy()
method into onStop
callback of your MainActivity
is a good practice.
client.destroy()
After destroy()
has been called, any subsequent invocations to the client.getTreatment()
or manager
methods result in control
or empty list respectively.
Important!
A call to the destroy()
method also destroys the factory object. When creating new client instance, first create a new factory instance.
Multiple evaluations at once
In some instances, you may want to evaluate treatments for multiple splits at once. Use the GetTreatments
method of the Split client to do this. Simply pass a list of the split names you want treatments for and the method returns an object with the results.
List<String> splitNames = Lists.newArrayList("SPLIT_NAME_1", "SPLIT_NAME_2");
Map<String, String> treatments = client.getTreatments(splitNames, null);
// treatments will have the following form:
// {
// "SPLIT_NAME_1": "on",
// "SPLIT_NAME_2": "visa"
// }
Attribute syntax
To target based on custom attributes, the SDK's getTreatment
method needs to be passed an attribute map at runtime.
In the example below, we are rolling out a split to users. The provided attributes plan_type
, registered_date
, permissions
, paying_customer
, and deal_size
are passed to the getTreatment
call. These attributes are compared and evaluated against the attributes used in the Rollout plan as defined in the Split Web console to decide whether to show the on
or off
treatment to this account.
The getTreatment
method supports five types of attributes: strings, numbers, dates, booleans, and sets. The proper data type and syntax for each are:
- Strings: Use type String.
- Numbers: Use type
java.lang.Long
orjava.lang.Integer
. - Dates: Express the value in
milliseconds since epoch
. In Java,milliseconds since epoch
is of typejava.lang.Long
. For example, the value for theregistered_date
attribute below isSystem.currentTimeInMillis()
, which is a long. - Booleans: Use type
java.lang.boolean
. - Sets: Use type
java.util.Collection
.
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("plan_type", "growth");
attributes.put("registered_date", System.currentTimeMillis());
attributes.put("deal_size", 1000);
attributes.put("paying_customer", true);
String[] perms = {"read", "write"};
attributes.put("permissions",perms);
// See client initialization above
String treatment = client.getTreatment("SPLIT_NAME", attributes);
if (treatment.equals("on")) {
// insert on code here
} else if (treatment.equals("off")) {
// insert off code here
} else {
// insert control code here
}
Get Treatments with Configurations
To leverage dynamic configurations with your treatments, you should use the getTreatmentWithConfig
method.
This method will return an object containing the treatment and associated configuration.
The config element will be a stringified version of the configuration JSON defined in the Split web console. If there is no configuration defined for a treatment, the SDK will return null
for the config parameter.
This method takes the exact same set of arguments as the standard getTreatment
method. See below for examples on proper usage:
SplitResult result = cli.getTreatmentWithConfig("new_boxes", attributes);
Gson gson = new Gson();
Map map = gson.fromJson(result.config(), Map.class);
String treatment = result.treatment();
If you need to get multiple evaluations at once, you can also use the getTreatmentsWithConfig
. The method takes the exact same arguments as the getTreatments
method but just returns a mapping of split names to splitResults instead of strings. Example usage below.
List<String> splitNames = Lists.newArrayList("SPLIT_NAME_1", "SPLIT_NAME_2");
Map<String, String> treatments = client.getTreatmentsWithConfig(splitNames, null);
// treatments will have the following form:
// {
// "SPLIT_NAME_1": { "treatment": "on", "config": "{ \"color\":\"red\" }" },
// "SPLIT_NAME_2": { "treatment": "visa", "config": "{ \"color\":\"red\" }" }
// }
Track
Use the track
method to record any actions your customers perform. Each action is known as an event
and corresponds to an event type
. Calling track
through one of our SDKs or via the API is the first step to getting experimentation data into Split and allows you to measure the impact of your splits on your users' actions and metrics.
Learn more about using track events in splits. FIX URL
In the examples below you can see that the .track()
method can take up to four arguments. The proper data type and syntax for each are:
- TRAFFIC_TYPE: The traffic type of the key in the track call. The expected data type is String. You can only pass values that match the names of traffic types that you have defined in your instance of Split.
- EVENT_TYPE: The event type that this event should correspond to. The expected data type is String. Full requirements on this argument are:
- Contains 80 characters or fewer.
- Starts with a letter or number.
- Contains only letters, numbers, hyphen, underscore, or period.
- This is the regular expression we use to validate the value:
[a-zA-Z0-9][-_.:a-zA-Z0-9]{0,79}
- VALUE: (Optional) The value to be used in creating the metric. This field can be sent in as null or 0 if you intend to purely use the count function when creating a metric. The expected data type is Float.
- PROPERTIES: (Optional) A Map of key value pairs that can be used to filter your metrics. Learn more about event property capture here. Split currently supports three types of properties: strings, numbers, and booleans.
The track
method returns a boolean value of true
or false
to indicate whether or not the SDK was able to successfully queue the event to be sent back to Split's servers on the next event post. The SDK will return false
if the current queue size is equal to the config set by eventsQueueSize
or if an incorrect input to the track
method has been provided.
In the case that a bad input has been provided, you can read more about our SDK's expected behavior here
// If you would like to send an event without a value
boolean trackEvent = client.track("TRAFFIC_TYPE", "EVENT_TYPE");
// Example
boolean trackEvent = client.track("user", "page_load_time");
// If you would like to associate a value to an event
boolean trackEvent = client.track("TRAFFIC_TYPE", "EVENT_TYPE", VALUE);
// Example
boolean trackEvent = client.track("user", "page_load_time", 83.334);
// If you would like to send an event but you've already defined the traffic type in the config of the client
boolean trackEvent = client.track("EVENT_TYPE");
// Example
boolean trackEvent = client.track("page_load_time");
// If you would like to associate a value to an event and you've already defined the traffic type in the config of the client
boolean trackEvent = client.track("EVENT_TYPE", VALUE);
// Example
boolean trackEvent = client.track("page_load_time", 83.334);
// If you would like to associate a value and properties to an event
boolean trackEvent = client.track("key", "TRAFFIC_TYPE", "EVENT_TYPE", VALUE, {PROPERTIES});
// Example
HashMap<String, Object> properties = new HashMap<>();
properties.put("package", "premium");
properties.put("admin", true);
properties.put("discount", 50);
boolean trackEvent = client.track("john@doe.com", "user", "page_load_time", 83.334, properties);
// If you would like to associate just properties to an event
boolean trackEvent = client.track("key", "TRAFFIC_TYPE", "EVENT_TYPE", null, {PROPERTIES});
// Example
HashMap<String, Object> properties = new HashMap<>();
properties.put("package", "premium");
properties.put("admin", true);
properties.put("discount", 50);
boolean trackEvent = client.track("john@doe.com", "user", "page_load_time", null, properties);
Configuration
The SDK has a number of knobs for configuring performance. Each knob is tuned to a reasonable default. However, you can override the value while instantiating the SDK. The parameters available for configuration are shown below.
Configuration | Description | Default value |
---|---|---|
featuresRefreshRate | The SDK polls Split servers for changes to feature splits at this rate (in seconds). | 3600 seconds |
segmentsRefreshRate | The SDK polls Split servers for changes to segments at this rate (in seconds). | 1800 seconds |
impressionsRefreshRate | The treatment log captures which customer saw what treatment (on, off, etc.) at what time. This log is periodically flushed back to Split servers. This configuration controls how quickly the cache expires after a write (in seconds). | 1800 seconds |
metricsRefreshRate | The SDK caches diagnostic data that it periodically sends to Split servers. This configuration controls how frequently this data is sent back to Split servers (in seconds). | 1800 seconds |
eventsQueueSize | When using .track , the number of events to be kept in memory. |
10000 |
eventFlushInterval | When using .track , how often is the events queue flushed to Split's servers. |
1800 seconds |
eventsPerPush | Maximum size of the batch to push events. | 2000 |
trafficType | When using .track , the default traffic type to be used. |
not set |
connectionTimeOutInMs | HTTP client connection timeout (in ms). | 15000ms |
readTimeoutInMs | HTTP socket read timeout (in ms). | 15000ms |
impressionsQueueSize | Default queue size for impressions. | 30K |
labelsEnabled | Disable labels from being sent to Split backend. Labels may contain sensitive information. | true |
enableDebug | Enabled verbose mode. | false |
proxyHost | The location of the proxy using standard URI: scheme://user:password@domain:port/path . If no port is provided the SDK will default to port 80. |
null |
ready | Maximum amount of time in milliseconds to wait before notifying a timeout. | -1 (not set) |
synchronizeInBackground | Activates synchronization when application host is in background. | false |
backgroundSyncPeriod | Rate in minutes in which the background synchronization would check the conditions and trigger the data fetch if those are met. Minimum rate allowed is 15 minutes. | 15 |
backgroundSyncWhenBatteryNotLow | When set to true, synchronize in background only if battery level is not low. | true |
backgroundSyncWhenWifiOnly | When set to true, synchronize in background only when the available connection is wifi (unmetered). When false background synchronization takes place as long as there is an available connection. | false |
streamingEnabled | Boolean flag to enable the streaming service as default synchronization mechanism when in foreground. In the event of an issue with streaming, the SDK will fallback to the polling mechanism. If false, the SDK will poll for changes as usual without attempting to use streaming. | true |
syncConfig | Optional SyncConfig instance. Use it to filter specific splits to be synced and evaluated by the SDK. These filters can be created with the SplitFilter::byName static function by passing a list of split names as string values and appended to this config using the SyncConfig builder. If not set or empty, all splits will be downloaded by the SDK. |
null |
To set each of the parameters defined above, use the syntax below.
import io.split.android.client.*;
import java.util.Arrays;
SplitFilter splitFilter = SplitFilter.byName(Arrays.asList("SPLIT_NAME_1", "SPLIT_NAME_2"));
SplitClientConfig config = SplitClientConfig.builder()
.impressionsRefreshRate(60)
.connectionTimeout(15000)
.readTimeout(15000)
.syncConfig(SyncConfig.builder()
.addSplitFilter(splitFilter)
.build())
.build();
//API Key
String apikey = "YOUR_API_KEY";
// Create a new user key to be evaluated
String matching = "key";
String bucketingKey = null;
Key k = new Key(matchingKey,bucketingKey);
// Create factory
SplitFactory splitFactory = SplitFactoryBuilder.build(apikey, k, config, getApplicationContext());
// Get Split Client instance
SplitClient client = splitFactory.client();
Localhost mode
Features start their life on one developer's machine. A developer should be able to put code behind splits on their development machine without the SDK requiring network connectivity. To achieve this, the Split SDK can be started in localhost mode (aka off-the-grid mode). In this mode, the SDK neither polls nor updates Split servers. Instead, it uses an in-memory data structure to determine what treatments to show to the logged in customer for each of the features.
Here is how you can start the SDK in localhost mode.
Since version 2.2.0, our SDK supports a new type of localhost split definition file, using the YAML format.
This new format allows the user to map different keys to different treatments within a single split, and also add configurations to them.
The new format is a list of single-key maps (one per mapping split-keys-config), defined as follows:
# - feature_name:
# treatment: "treatment_applied_to_this_entry"
# keys: "single_key_or_list"
# config: "{\"desc\" : \"this applies only to ON treatment\"}"
- my_feature:
treatment: "on"
keys: "key"
config: "{\"desc\" : \"this applies only to ON treatment\"}"
- some_other_feature:
treatment: "off"
- my_feature:
treatment: "off"
- other_feature:
treatment: "off"
keys: ["key_1", "key_2"]
config: "{\"desc\" : \"this overrides multiple keys and returns off treatment for those keys\"}"
In the example above, we have 3 entries:
- The first one defines that for split
my_feature
, the keykey
will return the treatmenton
and theon
treatment will be tied to the configuration{"desc" : "this applies only to ON treatment"}
. - The second entry defines that the feature
some_other_feature
will always return theoff
treatment and no configuration. - The third entry defines that
my_feature
will always returnoff
for all keys that don't match another entry (in this case, any key other thankey
). - The forth entry shows how an example to override a treatment for a set of keys.
In this mode, the SDK loads the yaml file from a resource bundle file at the assets' project src/main/assets/splits.yaml
.
import io.split.android.client.SplitClient;
import io.split.android.client.SplitFactoryBuilder;
import io.split.android.client.api.Key;
// Create a new user key to be evaluated
String matching = "key";
String bucketingKey = null;
Key k = new Key(matchingKey,bucketingKey);
SplitClient client = SplitFactoryBuilder.build("localhost", k, getApplicationContext()).client();
If a split.yaml or split.yml is not found in assets, Split SDK maintains backward compatibility by trying to load the legacy file (split.properties), now deprecated.
The format of this file is a properties file as key-value line. The key is the split name, and the value is the treatment name. Here is a sample split.properties
file.
# this is a comment
# sdk.getTreatment(*, reporting_v2) will return 'on'
reporting_v2=on
double_writes_to_cassandra=off
new-navigation=v3
Manager
Use the Split Manager to get a list of features available to the Split client.
To instantiate a Manager in your code base, use the same factory that you used for your client.
SplitFactory splitFactory = SplitFactoryBuilder.build("YOUR_API_KEY");
SplitManager manager = splitFactory.manager();
The Manager then has the following methods available.
/**
* Retrieves the Splits that are currently registered with the
* SDK.
*
* @return a List of SplitView or empty.
*/
List<SplitView> splits();
/**
* Returns the Splits registered with the SDK of this name.
*
* @return SplitView or null
*/
SplitView split(String SplitName);
/**
* Returns the names of features (or Splits) registered with the SDK.
*
* @return a List of String (Split Feature Names) or empty
*/
List<String> splitNames();
The SplitView
object referenced above has the following structure.
public class SplitView {
public String name;
public String trafficType;
public boolean killed;
public List<String> treatments;
public long changeNumber;
}
Listener
Split SDKs send impression data back to Split servers periodically and as a result of evaluating splits. To additionally send this information to a location of your choice, define and attach an impression listener.
The SDK sends the generated impressions to the impression listener right away. As a result, be careful while implementing handling logic to avoid blocking the main thread. Generally speaking, you should create a separate thread to handle incoming impressions (see the snippet below).
SplitClientConfig config = SplitClientConfig.builder()
.impressionListener(new MyImpressionListener())
.build();
class MyImpressionListener implements ImpressionListener {
@Override
public void log(Impression impression) {
// Do something on UI thread
new Thread(new Runnable() {
public void run() {
// Do something in another thread (use this most of the time!)
}
}).start();
}
@Override
public void close() {
}
}
Flush
The flush() method sends the data stored in memory (impressions and events) to Split cloud and clears the successfully posted data. If a connection issue is experienced, the data will be sent on the next attempt.
If you want to flush all pending data when your app goes to background, a good place to call this method would be the onPause callback of your MainActivity.
client.flush()
Advanced: Subscribe to events
You can listen for three different types of events from the SDK.
SDK_READY_FROM_CACHE
- The SDK is ready to evaluate using the locally cached data (which might be stale). If there is data in the cache, this event will be emitted almost immediately since access to the local cache is fast. Otherwise it won't fire.SDK_READY
is fired when the SDK has the necessary evaluation information. If the last known configuration is in the disk cache, this event is triggered immediately. If this is the first time the SDK is instantiated, this event is triggered when the SDK has all the information requested from our servers.SDK_READY_TIMED_OUT
is fired if there is no last known configuration in disk cache, and the SDK could not acquire the information from our servers after a given period of time, determined byready
in theSplitClientConfig
.
An event is simply an extension of a SplitEventTask.
public class SplitEventTask {
public void onPostExecution(SplitClient client) { }
public void onPostExecutionView(SplitClient client) { }
}
onPostExecution
is executed in the background when the event is triggered. This step is used to perform background computation, which can take a long time.
onPostExecutionView
is invoked on the UI thread after onPostExecution
finishes.
The syntax to listen for an event can be seen below.
client.on(SplitEvent.SDK_READY, new SplitEventTask() {
@Override
public void onPostExecutionView(SplitClient client) {
//UI Code in Here
}
});
]
Comments
0 comments
Please sign in to leave a comment.