Documentation
NAV Navbar
  • Android SDK
  • Android SDK

    Introduction

    Welcome to the developer documentation for the Kameleoon Android SDK! Our SDK gives you the possibility of running experiments on native mobile Android applications. Integrating our SDK into your applications is relatively easy, and its footprint (in terms of memory and network usage) is low.

    You can refer to the SDK reference to check out all possible features of the SDK. Also make sure you check out our Getting started tutorial which we have prepared to walk you through the installation and implementation.

    Getting started

    This guide is designed to help you integrate our SDK in a few minutes and start running experiments in your Android apps. This tutorial will explain the setup of a simple A/B test to change the number of recommended products based on different variations.

    Creating an experiment

    First, you must create an experiment in the Kameleoon back-office so that our platform is aware of the new A/B test you're planning to implement on your side. Make sure that server-side type is chosen as shown below:

    Server-side experiment

    Upon successful creation of the experiment, you will need to get its ID to use in the SDK as an argument to the triggerExperiment() method. So the next step is to open the Kameleoon editor and login with your credentials. Click on Open an existing experiment and select the experiment you just created from the list. This will open a pop up with the experiment details as well as its ID.

    Installing the SDK

    repositories {
        maven {
            url "http://artifacts.kameleoon.net:8081/artifactory/sdk-libs-release-local"
            credentials {
                username "sdk-puller"
                password "AP48PakWgwqfg3w5VQijE984jkXnrHhp2T2kTJn6ugWY14CeccCaWGCaqkvV"
            }
        }
    }
    dependencies {
        implementation 'com.kameleoon:kameleoon-client-android:1.1.2'
    }
    

    You can install the Android SDK using by adding the following code into your build.gradle file as shown in the example to the right.

    Initializing the Kameleoon Client

    import android.app.Application;
    
    import com.kameleoon.ssx.KameleoonClient;
    import com.kameleoon.ssx.KameleoonClientFactory;
    
    public class MyApplication extends Application
    {
        private KameleoonClient kameleoonClient;
    
        @Override
        public void onCreate() {
            super.onCreate();
            kameleoonClient = KameleoonClientFactory.create("a8st4f59bj", getApplicationContext());
        }
    
        public KameleoonClient getKameleoonClient() {
            return kameleoonClient;
        }
    }
    

    After installing the SDK into your application and setting up a server-side experiment on Kameleoon's back-office, the next step is to create the Kameleoon client.

    The code on the right gives a clear example. A Client is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you will need to run an experiment.

    While executing the KameleoonClientFactory.create() method initializes the client, on Android it is not immediately ready for use. This is because the current configuration of experiments (along with their traffic repartition) has to be retrieved from a Kameleoon remote server. This requires network access, which is not always available. Until the Kameleoon client is fully ready, you should not try to run any other method in our SDK. Note that once the first configuration of experiments is fetched, it is then periodically refreshed, but even if the refresh fails for any reason, the Kameleoon client will still be ready and working (but on an outdated / previous configuration).

    We provide the isReady() method to check if the Kameleoon client initialization is finished.

    Alternatively, we provide a helper callback to encapsulate the logic of experiment triggering and variation implementation. Which approach (isReady() or callback) is best to use depends on your own preferences and on the exact use case at hand. As a rule of thumb, we recommend using isReady() when it is expected that the SDK will indeed be ready for use. For instance, if you are running an experiment on some dialog that would be accessible only after a few seconds / minutes of navigation within the application. And we recommend using the callback when there is a high probability that the SDK is still in the process of initialization. For instance, an experiment that would take place at the application launch would be better treated with a callback that would make the application wait until either the SDK is ready or a specified timeout has expired.

    Triggering an experiment

    Running an A/B experiment on your Android application means bucketing your users into several groups (one per variation). The SDK takes care of this bucketing (and the associated reporting) automatically.

    Triggering an experiment by calling the triggerExperiment() method will register a random variation for a given userID. If this userID is already associated with a variation (most likely a returning visitor that has already been exposed to the experiment previously), then it will return the previous variation associated with the given experiment.

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    import com.kameleoon.ssx.Data;
    import com.kameleoon.ssx.KameleoonClient;
    
    public class MainActivity extends AppCompatActivity {
        private MyApplication myApplication;
    
        private TextView mTextMessage;
        private int recommendedProductsNumber;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            myApplication = (MyApplication) getApplication();
            KameleoonClient kameleoonClient = myApplication.getKameleoonClient();
            String variationID;
    
            if (kameleoonClient.isReady()) {
                try {
                    String userID = UUID.randomUUID().toString(); // usually, this would be the internal ID of this user
                    variationID = kameleoonClient.triggerExperiment(userID, 75253);
                }
                catch (KameleoonException.SDKNotReady | KameleoonException.ExperimentConfigurationNotFound e) {
                    // The user will not be counted into the experiment, but should see the reference variation
                    variationID = "reference";
                }
            }
            else {
                // The SDK is not ready, so the user is "out of the experiments". This is the same as if he was bucketed into the reference
                variationID = "reference";
            }
    
            if (variationID.equals("reference")) {
                //This is the default / reference number of products to display
                recommendedProductsNumber = 5;
            }
            else if (variationID.equals("148382")) {
                //We are changing number of recommended products for this variation to 10
                recommendedProductsNumber = 10;
            }
            else if (variationID.equals("187791")) {
                //We are changing number of recommended products for this variation to 8
                recommendedProductsNumber = 8;
            }
    
            setContentView(R.layout.activity_main);
            mTextMessage = (TextView) findViewById(R.id.message);
            mTextMessage.setText("Number of recommended products displayed: " + recommendedProductsNumber + " products.");
        }
    }
    

    We provide two code samples to illustrate the triggering of an experiment. The first one uses the isReady() approach. It's a bit simpler.

    package com.example.mytestapplication;
    
    import android.annotation.SuppressLint;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.widget.TextView;
    
    import com.kameleoon.ssx.KameleoonClient;
    import com.kameleoon.ssx.KameleoonException;
    import com.kameleoon.ssx.KameleoonReadyCallback;
    
    public class MainActivity extends AppCompatActivity {
    
        private TextView mTextMessage;
        private KameleoonClient kameleoonClient;
        private MainApplication mainApplication;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            mainApplication = (MainApplication) getApplication();
            kameleoonClient = mainApplication.getKameleoonClient();
            setContentView(R.layout.activity_main);
            mTextMessage = (TextView) findViewById(R.id.message);
    
            kameleoonClient.runWhenReady(new ExampleKameleoonCallback(), 1000);
        }
    
        private class ExampleKameleoonCallback implements KameleoonReadyCallback
        {
            private String variationID;
            private int recommendedProductsNumber;
    
            @Override
            public void onReady() {
                try {
                    String userID = UUID.randomUUID().toString(); // usually, this would be the internal ID of this user
                    variationID = kameleoonClient.triggerExperiment(userID, 75253);
                } catch (KameleoonException.SDKNotReady | KameleoonException.ExperimentConfigurationNotFound exception) {
                    variationID = "reference";
                }
    
                if (variationID.equals("reference")) {
                    //This is the default / reference number of products to display
                    recommendedProductsNumber = 5;
                }
                else if (variationID.equals("216713")) {
                    //We are changing number of recommended products for this variation to 10
                    recommendedProductsNumber = 10;
                }
                else if (variationID.equals("216712")) {
                    //We are changing number of recommended products for this variation to 8
                    recommendedProductsNumber = 8;
                }
    
                applyVariation();
            }
    
            @Override
            public void onTimeout() {
                variationID = "reference";
                recommendedProductsNumber = 5;
                applyVariation();
            }
    
            @SuppressLint("SetTextI18n")
            private void applyVariation()
            {
                mTextMessage.setText("Number of recommended products displayed: " + recommendedProductsNumber + " products.");
            }
        }
    }
    

    This is a second example with the callback runWhenReady() approach. You need to implement code both in the onReady() and onTimeout() methods. Note that here we used a timeout of 1000 milliseconds.

    Implementing variation code

        private int recommendedProductsNumber;
    
        if (variationID.equals("reference")) {
            //This is the default / reference number of products to display
            recommendedProductsNumber = 5;
        }
        else if (variationID.equals("148382")) {
            //We are changing the number of recommended products for this variation to 10
            recommendedProductsNumber = 10;
        }
        else if (variationID.equals("187791")) {
            //We are changing the number of recommended products for this variation to 8
            recommendedProductsNumber = 8;
        }
    

    To execute different code paths depending on the variation assigned to the visitor, you will need the list of all the experiment's variation IDs. You can find these variation IDs by going into the Kameleoon Editor as shown below.

    Once you have the IDs of the different variations, you can implement a different action for each variation, and one of the code paths will be executed, based on the associated variationID for the current visitor. Generally, this can be done using a simple if / else or switch mechanism. In our example, we just change the number of recommended products with two different variations.

    Get variationID

    Tracking conversion

    String userID = UUID.randomUUID().toString();
    int goalID = 83023;
    
    kameleoonClient.trackConversion(userID, goalID, 10f);
    

    After you are done with triggering an experiment, the next step is usually to start tracking conversions. This is done to measure performance characteristics according to the goals that make sense for your business.

    For this purpose, use the trackConversion() method of the SDK as shown in the example. You need to pass the userID and goalID parameters so we can correctly track conversion for this particular user.

    Get goalID

    Obtaining results

    Once your implementation is in place on the mobile app side (experiment triggering, variations handling, and conversion tracking), it is time to launch the experiment on the Kameleoon platform. You do this in the same way as for a front-end test. Basic operations such as starting, pausing and stopping the experiment work in exactly the same way.

    After the experiment has been launched, the first results will be available on our standard results page in the back-office after a duration of 30 minutes. This is because (as is the case with front-end testing) visits are considered over after 30 minutes of inactivity. Inactivity in this context means the absence of calls sent to the Kameleoon back-end servers (such calls are made via triggerExperiment(), trackConversion() or flush() methods).

    Reference

    This is a full reference documentation of the Android SDK.

    If this is your first time working with the Android SDK, we strongly recommend you go over our Getting started tutorial to integrate the SDK and start experimenting in a few minutes.

    Initialization: creating the Kameleoon Client

    kameleoonClient = KameleoonClientFactory.create(siteCode, getApplicationContext());
    

    The starting point for using the SDK is the initialization step. All interaction with the SDK is done through an object named KameleoonClient, therefore you need to create this object.

    Arguments

    NameTypeDescription
    siteCodeStringCode of the website you want to run experiments on. This unique code id can be found in our platform's back-office. This field is mandatory.
    contextandroid.content.ContextContext of the Android application. This field is mandatory.

    Checking that the Kameleoon Client is properly initialized

    Boolean ready = kameleoonClient.isReady();
    

    For mobile SDKs, the initialization of the Kameleoon Client is not immediate, as it needs to perform a server call to retrieve the current configuration for all active experiments. It is recommended to check if the SDK is ready by calling this method before triggering an experiment. Alternatively, you could setup exception catching around the triggerExperiment() method to look for the KameleoonException.SDKNotReady exception, or you could use the runWhenReady() method with a callback as detailed in the next paragraph.

    Arguments

    NameTypeDescription

    Return value

    NameTypeDescription
    readybooleanBoolean representing the status of the SDK (properly initialized, or not yet ready to be used).

    Waiting until the Kameleoon Client is initialized

    kameleoonClient.runWhenReady(new ExampleKameleoonCallback(), 1000);
    
    private class ExampleKameleoonCallback implements KameleoonReadyCallback
    {
        private String variationID;
        private int recommendedProductsNumber;
    
        @Override
        public void onReady() {
            try {
                variationID = kameleoonClient.triggerExperiment(mainApplication.getUserId(), 75253L);
            } catch (KameleoonException.SDKNotReady | KameleoonException.ExperimentConfigurationNotFound exception) {
                variationID = "reference";
            }
    
            if (variationID.equals("reference")) {
                //This is the default / reference number of products to display
                recommendedProductsNumber = 5;
            }
            else if (variationID.equals("216713")) {
                //We are changing the number of recommended products for this variation to 10
                recommendedProductsNumber = 10;
            }
            else if (variationID.equals("216712")) {
                //We are changing the number of recommended products for this variation to 8
                recommendedProductsNumber = 8;
            }
    
            applyVariation();
        }
    
        @Override
        public void onTimeout() {
            variationID = "reference";
            recommendedProductsNumber = 5;
            applyVariation();
        }
    
        @SuppressLint("SetTextI18n")
        private void applyVariation()
        {
            mTextMessage.setText("Number of recommended products displayed: " + recommendedProductsNumber + " products.");
        }
    }
    

    For mobile SDKs, the initialization of the Kameleoon Client is not immediate, as it needs to perform a server call to retrieve the current configuration for all active experiments. The runWhenReady() method of the KameleoonClient class allows to pass a callback that will be executed as soon as the SDK is ready for use. It also allows the use of a timeout.

    The callback given as first argument to this method must be a member of a class implementing the KameleoonReadyCallback interface. Two methods must be implemented: onReady() and onTimeout(). The onReady() method will be called once the Kameleoon client is ready, and should contain code triggering an experiment and implementing variations. The onTimeout() method will be called if the specified timeout happens before the client is initialized. Usually it should contain code implementing the "reference" variation, as the user will be "out of the experiment" if a timeout takes place.

    Arguments

    NameTypeDescription
    callbackKameleoonReadyCallbackCallback object. This field is mandatory.
    timeoutintTimeout (in milliseconds). This field is optional, if not provided, it will use the default value of 2000 milliseconds.

    Triggering experiments

    String userID = UUID.randomUUID().toString();
    int experimentID = 75253;
    String variationID;
    
    try {
        variationID = kameleoonClient.triggerExperiment(userID, experimentID);
    }
    catch (KameleoonException.SDKNotReady | KameleoonException.ExperimentConfigurationNotFound e) {
        // The user will not be counted into the experiment, but should see the reference variation
        variationID = "reference";
    }
    catch (Exception e) {
        // This is generic Exception handler which will handle all exceptions.
        System.out.println("Exception occurred");
    }
    

    To trigger an experiment, call the triggerExperiment() method of our SDK.

    This method takes userID and experimentID as mandatory arguments to register a variation for a given user.

    If such a user has never been associated with any variation, the SDK returns a randomly selected variation. In case a user with a given userID is already registered with a variation, it will detect the previously registered variation and return the variationID.

    You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

    Arguments

    NameTypeDescription
    userIDStringUnique identifier of the user. This field is mandatory.
    experimentIDStringID of the experiment you want to expose to a user. This field is mandatory.

    Return value

    NameTypeDescription
    variationIDStringID of the variation that is registered for the given userID.

    Exceptions Thrown

    TypeDescription
    KameleoonException.SDKNotReadyException indicating that the SDK has not completed its initialization yet.
    KameleoonException.ExperimentConfigurationNotFoundException indicating that the requested experiment ID has not been found in the internal configuration of the SDK. This is usually normal and means that the experiment has not yet been started on Kameleoon's side (but code triggering and variation implementations are already deployed on the mobile app's side).

    Tracking Conversion

    String userID = UUID.randomUUID().toString();
    int goalID = 83023;
    
    kameleoonClient.addData(
        userID,
        new Data.Interest(2)
    );
    kameleoonClient.addData(userID, new Data.Conversion(32, 0f, false));
    
    kameleoonClient.trackConversion(userID, goalID);
    

    To track conversion, use the trackConversion() method. This method requires userID and goalID to track conversion on this particular goal. In addition, this method also accepts revenue as a third optional argument to track revenue. The userID usually is identical to the one that was used when triggering the experiment.

    The trackConversion() method doesn't return any value. This method is non-blocking as the server call is made asynchronously.

    Arguments

    NameTypeDescription
    userIDStringUnique identifier of the user. This field is mandatory.
    goalIDintID of the goal. This field is mandatory.
    revenuefloatRevenue of the conversion. This field is optional.

    Saving data

    kameleoonClient.addData(
        userID,
        new Data.Interest(0),
        new Data.Custom(1, "some custom value")
    );
    kameleoonClient.addData(userID, new Data.Conversion(32, 10f, false));
    

    To associate data with the current user, we can use the addData() method. This method requires the userID as a first parameter, and then accepts several additional parameters. Those additional parameters represent the various Data Types allowed in Kameleoon.

    Note that the addData() method doesn't return any value and doesn't interact with the Kameleoon back-end servers by itself. Instead, all declared data is saved for further sending via the flush() method described in the next paragraph. This reduces the number of server calls made, as data is usually grouped into a single server call triggered by the execution of flush().

    Arguments

    NameTypeDescription
    userIDStringUnique identifier of the user. This field is mandatory.
    dataTypesDataCustom data types which may be passed separated by a comma.

    Data Types

    Conversion Data Type

    kameleoonClient.addData(userID, new Data.Conversion(32, 0f, false));
    
    NameTypeDescription
    goalIDintID of the goal. This field is mandatory.
    revenuefloatConversion revenue. This field is optional.
    negativebooleanDefines if the revenue is positive or negative. This field is optional.

    Custom Data Type

    kameleoonClient.addData(
        userID,
        new Data.Custom(1, "some custom value")
    );
    
    NameTypeDescription
    indexintIndex / ID of the custom data to be stored. This field is mandatory.
    valueStringValue of the custom data to be stored. This field is mandatory.

    Interest Data Type

    kameleoonClient.addData(
        userID,
        new Data.Interest(0)
    );
    
    NameTypeDescription
    indexintIndex of the interest. This field is mandatory.

    Flushing saved data

    String userID = UUID.randomUUID().toString();
    
    kameleoonClient.addData(
        userID,
        new Data.Interest(0)
    );
    kameleoonClient.addData(userID, new Data.Conversion(32, 0f, false));
    
    kameleoonClient.flush(userID);
    

    Data associated with the current user via the addData() method is not immediately sent to the server. It is stored and accumulated until it is sent automatically by the triggerExperiment() or trackConversion() methods, or manually by the flush() method. This allows the developer to control exactly when the data is flushed to our servers. For instance, if you call the addData() method a dozen times, it would be a waste of ressources to send data to the server after each addData() invocation. Just call flush() once at the end.

    The flush() method doesn't return any value. This method is non-blocking as the server call is made asynchronously.

    Arguments

    NameTypeDescription
    userIDStringUnique identifier of the user. This field is mandatory.