Dev guideAPI Reference
Dev guideAPI ReferenceUser GuideGitHubNuGetDev CommunitySubmit a ticketLog In
GitHubNuGetDev CommunitySubmit a ticket

Initialize the Android SDK

Lists the steps required to initialize the Optimizely Feature Experimentation Android SDK into your application.

Use the instantiate method to initialize the Android SDK and instantiate an instance of the Optimizely client class that exposes API methods like Decide methods. Each client corresponds to the datafile representing the state of a project for a certain environment.

In the Android SDK, you do not need to manage the datafile directly. The SDK has an additional abstraction called a manager that handles getting the datafile and instantiating the client for you during the SDK's initialization process. The manager includes support for datafile polling to update the datafile on a regular interval automatically.

Version

4.0.0 and higher

Description

The constructor accepts a configuration object to configure Optimizely.

Some parameters are optional because the SDK provides a default implementation, but you may want to override these for your production environments. For example, you may want to override these to set up an error handler and logger to catch issues, an event dispatcher to manage network calls, and a User Profile Service to ensure sticky bucketing.

Parameters

The table below lists the required and optional parameters in Android (client constructed using Builder class and passing the following to Build()).

ParameterTypeDescription
SDK Key
required
stringThe SDK key is used to define the config file for the environment
eventProcessor
optional
EventProcessorAn event handler object provides an intermediary processing stage for events. The EventProcessor dispatches events via a provided EventHandler.
eventHandler
optional
EventHandlerAn event handler dispatching events to the Optimizely event end-point.
logger
optional
LoggerA logger implementation to log messages.
errorHandler
optional
ErrorHandlerAn error handler object to handle errors.
userProfileService
optional
UserProfileServiceA user profile service. An object with lookup and save methods.
datafileDownloadInterval
optional
longSets the interval (in the specified TimeUnit) at which DatafileHandler will attempt to update the cached datafile periodically.

If this value is not set, background updates are disabled.

The minimum interval is 15 minutes (enforced by the Android JobScheduler API).
eventDispatchInterval
optional
longSets the interval (in the specified TimeUnit) in which queued events will be flushed periodically.

If this value is not set, the default interval will be used (30 seconds).
defaultDecideOptions
optional
ArrayAn array of OptimizelyDecideOption enums. When the Optimizely client is constructed with this parameter, it sets default decide options applied to all the Decide calls made during the lifetime of the Optimizely client. Additionally, you can pass options to individual Decide methods (does not overrides defaults).

For details on decide options, see OptimizelyDecideOption.
ODPDisabled
optional
The Android SDK enables the Advanced Audience Targeting methods by default. But, the methods do nothing unless you have enabled and configured the Advanced Audience Targeting integration.

Disable the Advanced Audience Targeting integration.
ODPSegmentCacheSize
optional
intOverride the default ODP segment cache size (100)
ODPSegmentCacheTimeout
optional
intOverride the default ODP segment cache timeout (10 minutes).
timeoutForODPSegmentFetch
optional
intOverride the default timeout of ODP segment fetch (10 seconds).
timeoutForODPEventDispatch
optional
intOverride the default timeout of ODP event dispatch (10 seconds).
ODPEventManager
optional
ODPEventManagerProvide an optional custom ODPEventManager instance.
ODPSegmentManager
optional
ODPSegmentManagerProvide an optional custom ODPSegmentManager instance.

Customize ODPManager

OdpManager contains all the logic supporting Advanced Audience Targeting-related features, including audience segments.

The Android SDK enables the Advanced Audience Targeting methods by default. But, the methods do nothing unless you have enabled and configured the Advanced Audience Targeting integration.

If necessary, to disable Advanced Audience Targeting altogether, call optimizelyManagerBuilder.withODPDisabled().

👍

Beta

Advanced Audience Targeting is currently in beta. Apply on the Optimizely beta signup page or contact your Customer Success Manager.

val disableODP = false // Setting this true will disable Advanced Audience Targeting  
val optimizelyManagerBuilder = OptimizelyManager.builder() 
  .withSDKKey("SDK_KEY_HERE") 
  .withDatafileDownloadInterval(15, TimeUnit.MINUTES) 
  .withEventDispatchInterval(60, TimeUnit.SECONDS) 
  .withTimeoutForODPEventDispatch(10) // in seconds 
  .withTimeoutForODPSegmentFetch(10) // in seconds 
  .withODPSegmentCacheSize(10) 
  .withODPSegmentCacheTimeout(10, TimeUnit.SECONDS) 
if (disableODP) { 
  optimizelyManagerBuilder.withODPDisabled() // This function will disable Advanced Audience Targeting
} 
val optimizelyManager = optimizelyManagerBuilder.build(applicationContext) 


// Instantiate a client synchronously with a bundled datafile 
val datafile = "REPLACE_WITH_YOUR_DATAFILE" 
val optimizelyClient = optimizelyManager.initialize(this, datafile) 


// Or, instantiate it asynchronously with a callback 
optimizelyManager.initialize(this, null) { client: OptimizelyClient? -> 
  // flag decision with userID (optional) 
  val user1 = optimizelyClient.createUserContext("USER_ID_HERE") 
  val decision = user1!!.decide("FLAG_KEY_HERE") 


  // flag decision with auto generated vuid 
  val user2 = optimizelyClient.createUserContext() 
  val decision2 = user2!!.decide("FLAG_KEY_HERE") 
} 
boolean disableODP = false; // Setting this true will disable the odp
OptimizelyManager.Builder optimizelyManagerBuilder = OptimizelyManager.builder()
       .withSDKKey("SDK_KEY_HERE")
       .withDatafileDownloadInterval(15, TimeUnit.MINUTES)
       .withEventDispatchInterval(60, TimeUnit.SECONDS)
       .withTimeoutForODPEventDispatch(10) // in seconds
       .withTimeoutForODPSegmentFetch(10) // in seconds
       .withODPSegmentCacheSize(10)
       .withODPSegmentCacheTimeout(10, TimeUnit.SECONDS);
if (disableODP) {
   optimizelyManagerBuilder.withODPDisabled(); // This function will disable the odp
}
OptimizelyManager optimizelyManager =
optimizelyManagerBuilder.build(getApplicationContext());

// Instantiate a client synchronously with a bundled datafile
String datafile = "REPLACE_WITH_YOUR_DATAFILE";
OptimizelyClient optimizelyClient = optimizelyManager.initialize(this, datafile);

// Or, instantiate it asynchronously with a callback
optimizelyManager.initialize(context, null, (OptimizelyClient client) -> {
    // flag decision with userID (optional)
    OptimizelyUserContext user1 = optimizelyClient.createUserContext("USER_ID_HERE");
    OptimizelyDecision decision = user1.decide("FLAG_KEY_HERE");

    // flag decision with auto generated vuid
    OptimizelyUserContext user2 = optimizelyClient.createUserContext();
    OptimizelyDecision decision = user2.decide("FLAG_KEY_HERE");

});

Example

The manager is implemented as a factory for Optimizely client instances. To use it, create a manager object by supplying your SDK key and optional configuration settings for datafile polling and datafile bundling. You can find the SDK key in the Settings > Environments tab.

Next, choose whether to instantiate the client synchronously or asynchronously and use the appropriate initialize method to instantiate a client.

If you use a bundled datafile, copy the datafile JSON string from the app. Typically you would want to copy the datafile string at the latest point possible pre-release.

// Build a manager
val optimizelyManager = OptimizelyManager.builder()
          .withSDKKey("<Your_SDK_Key>")
          .withDatafileDownloadInterval(15, TimeUnit.MINUTES)
          .withEventDispatchInterval(30, TimeUnit.SECONDS)
          .build(context)

// Instantiate a client synchronously with a bundled datafile
val datafile = "REPLACE_WITH_YOUR_DATAFILE"
val optimizelyClient = optimizelyManager.initialize(context, datafile)

// Or, instantiate it asynchronously with a callback
optimizelyManager.initialize(context, null) { client: OptimizelyClient ->
    // flag decision
    val user = client.createUserContext("<User_ID>")!!
    val decision = user.decide("<Flag_Key>")
}
// Build a manager
OptimizelyManager optimizelyManager = OptimizelyManager.builder()
       .withSDKKey("<Your_SDK_Key>")
       .withDatafileDownloadInterval(15, TimeUnit.MINUTES)
       .withEventDispatchInterval(30, TimeUnit.SECONDS)
       .build(context);

// Instantiate a client synchronously with a bundled datafile
String datafile = "REPLACE_WITH_YOUR_DATAFILE";
OptimizelyClient optimizelyClient = optimizelyManager.initialize(context, datafile);

// Or, instantiate it asynchronously with a callback
optimizelyManager.initialize(context, null, (OptimizelyClient client) -> {
    // flag decision
    OptimizelyUserContext user = client.createUserContext("<User_ID>");
    OptimizelyDecision decision = user.decide("<Flag_Key>");
});

See the Android example: _MainActivity.java.

Get a client

Each manager retains a reference to its most recently initialized client. You can use the getOptimizely function to return that instance.

If this method is called before any client objects have been initialized, a dummy client instance is created and returned. This dummy instance logs errors when any of its methods are used.

val optimizelyClient = optimizelyManager.optimizely
OptimizelyClient optimizelyClient = optimizelyManager.getOptimizely();

Use synchronous or asynchronous initialization

You have two choices for when to instantiate the Optimizely client: synchronous and asynchronous. The behavioral difference between the two methods is whether your application pings the Optimizely servers for a new datafile during initialization. The functional difference between the two methods is whether your app prioritizes accuracy or speed.

🚧

Important

You much decide to initialize the Android SDK either synchronously or asynchronously. You cannot use both initialization methods.

Synchronous initialization

The synchronous method prioritizes speed over accuracy. Instead of attempting to download a new datafile every time you initialize an Optimizely client, your app uses a local version of the datafile. This local datafile can be cached from a previous network request (see more about configuring datafile polling) or embedded within your app (see more about enabling bundled datafiles).

When you initialize a client synchronously, the Optimizely manager first searches for a cached datafile. If one is available, the manager uses it to complete the client initialization. If the manager can't find a cached datafile, the manager searches for a bundled datafile. If the manager finds a bundled datafile, it uses the datafile to complete the client initialization. If the manager cannot find a bundled datafile, the manager cannot initialize the client.

1200

To initialize an OptimizelyClient object synchronously, call OptimizelyManager#initialize() and provide two arguments:

  • The Application instance (from android.app.Application)
  • An Integer pointer to the application resource datafile

For more details on the specific requirements, view OptimizelyManager.java from the publicly available Android SDK.

Asynchronous initialization

The asynchronous method prioritizes accuracy over speed. During initialization, your app requests the newest datafile from the CDN servers. Requesting the newest datafile ensures that your app always uses the most current project settings, but it also means your app cannot instantiate a client until it downloads a new datafile, discovers the datafile has not changed, or until the request times out. This process takes time.

Initializing a client asynchronously executes like the synchronous initialization, except the manager will first attempt to download the newest datafile. This network activity is what causes an asynchronous initialization to take longer to complete.

If the network request returns an error (such as when network connectivity is unreliable) or if the manager discovers that the cached datafile is identical to the newest datafile, the manager then uses the synchronous approach. If the manager discovers that the datafile has been updated and now differs from the cached datafile, the manager downloads the new datafile and uses it to initialize the client.

1013

To initialize an OptimizelyClient object asynchronously, call OptimizelyManager#initialize() and three arguments:

  • The Application instance (from android.app.Application)
  • An Integer pointer to the application resource datafile
  • A listener object

For more details on the specific requirements and to see how to build each object, view OptimizelyManager.java from the publicly available Android SDK.

Configure datafile polling

During its initialization, the manager attempts to pull the newest datafile from the CDN servers. After this, the Optimizely manager can periodically check for and pull a new datafile at the time interval you set during its initialization. The process of checking for and downloading a new datafile is called datafile polling.

Datafile polling is disabled by default, so the manager only checks for a new datafile during initialization. To enable polling, set a non-zero interval value. This value is the number of seconds the manager waits between datafile polling attempts.

// Poll every 15 minutes
val optimizelyManager = OptimizelyManager.builder()
            .withSDKKey("<Your_SDK_Key>")
            .withDatafileDownloadInterval(15, TimeUnit.MINUTES)
            .build(context)
// Poll every 15 minutes
OptimizelyManager optimizelyManager = OptimizelyManager.builder()
        .withSDKKey("<Your_SDK_Key>")
        .withDatafileDownloadInterval(15, TimeUnit.MINUTES)
        .build(context);

Usage notes

  • The minimum polling interval is 900 secs (which is 15 minutes, enforced by the Android JobScheduler API)
  • Updated datafiles are automatically picked up because the default datafile handler now supports the ProjectConfigManager API.
  • You can register for datafile change notifications as well via the UpdateConfigNotification
optimizelyClient.addUpdateConfigNotificationHandler { notification ->
    println("got datafile change")
}
optimizelyClient.addUpdateConfigNotificationHandler(notification -> {
    System.out.println("got datafile change");
});

Click here to learn more about Automatic Datafile Management
To override the default datafile handler and use your own, implement DatafileHandler.

Enable bundled datafiles

When your customer opens your app for the first time after installing or updating it, the manager attempts to pull the newest datafile from Optimizely's CDN. If your app is unable to contact the servers, the manager can substitute a datafile that you included (bundled) when you created your app.

By bundling a datafile within your app, you ensure that the Optimizely manager can initialize without waiting for a response from the CDN. This lets you prevent poor network connectivity from causing your app to hang or crash while it loads.

Datafile bundling works with both synchronous and asynchronous initialization because reverting to a bundled datafile happens during the Optimizely manager's initialization before a client is instantiated.

// Initialize Optimizely asynchronously with a datafile.
//  If it is not able to download a new datafile, it will
//  initialize an OptimizelyClient with the one provided.

optimizelyManager.initialize(context, R.raw.datafile) { optimizelyClient: OptimizelyClient ->
    val user = optimizelyClient.createUserContext("<User_ID>")!!
    val decision = user.decide("<Flag_Key>")
}

// Initialize Optimizely synchronously
//  This will immediately instantiate and return an
//  OptimizelyClient with the datafile that was passed in.
//  It'll also download a new datafile from the CDN and
//  persist it to local storage.
//  The newly downloaded datafile will be used the next
//  time the SDK is initialized.

optimizelyManager.initialize(context, R.raw.datafile)
// Initialize Optimizely asynchronously with a datafile.
//  If it is not able to download a new datafile, it will
//  initialize an OptimizelyClient with the one provided.

optimizelyManager.initialize(context, R.raw.datafile, (OptimizelyClient optimizelyClient) -> {
    OptimizelyUserContext user = optimizelyClient.createUserContext("<User_ID>");
    OptimizelyDecision decision = user.decide("<Flag_Key>");
});

// Initialize Optimizely synchronously
//  This will immediately instantiate and return an
//  OptimizelyClient with the datafile that was passed in.
//  It'll also download a new datafile from the CDN and
//  persist it to local storage.
//  The newly downloaded datafile will be used the next
//  time the SDK is initialized.

optimizelyManager.initialize(context, R.raw.datafile);

More sample code

// Here are more sample codes for synchronous and asynchronous SDK initializations with multiple options

// [Synchronous]

// [S1] Synchronous initialization
//      1. SDK is initialized instantly with a cached (or bundled) datafile
//      2. A new datafile can be downloaded in background and cached after the SDK is initialized.
//         The cached datafile will be used only when the SDK re-starts in the next session.
optimizelyManager = OptimizelyManager.builder()
                .withSDKKey("<Your_SDK_Key>")
                .build(context)
optimizelyClient = optimizelyManager.initialize(context, R.raw.datafile)
user = optimizelyClient.createUserContext("<User_ID>")!!
decision = user.decide("<Flag_Key>")

// [S2] Synchronous initialization
//      1. SDK is initialized instantly with a cached (or bundled) datafile
//      2. A new datafile can be downloaded in background and cached after the SDK is initialized.
//         The cached datafile is used immediately to update the SDK project config.
optimizelyManager = OptimizelyManager.builder()
                .withSDKKey("<Your_SDK_Key>")
                .build(context)
optimizelyClient = optimizelyManager.initialize(context, R.raw.datafile, true, true)
user = optimizelyClient.createUserContext("<User_ID>")!!
decision = user.decide("<Flag_Key>")

// [S3] Synchronous initialization
//      1. SDK is initialized instantly with a cached (or bundled) datafile
//      2. A new datafile can be downloaded in background and cached after the SDK is initialized.
//         The cached datafile is used immediately to update the SDK project config.
//      3. Polling datafile periodically.
//         The cached datafile is used immediately to update the SDK project config.
optimizelyManager = OptimizelyManager.builder()
                .withSDKKey("<Your_SDK_Key>")
                .withDatafileDownloadInterval(15, TimeUnit.MINUTES)
                .build(context)
optimizelyClient = optimizelyManager.initialize(context, R.raw.datafile)
user = optimizelyClient.createUserContext("<User_ID>")!!
decision = user.decide("<Flag_Key>")

// [Asynchronous]

// [A1] Asynchronous initialization
//      1. A datafile is downloaded from the server and the SDK is initialized with the datafile
optimizelyManager = OptimizelyManager.builder()
                .withSDKKey("<Your_SDK_Key>")
                .build(context)
optimizelyManager.initialize(context, null) { client: OptimizelyClient ->
   val user = client.createUserContext("<User_ID>")!!
   val decision = user.decide("<Flag_Key>")
}

// [A2] Asynchronous initialization
//      1. A datafile is downloaded from the server and the SDK is initialized with the datafile
//      2. Polling datafile periodically.
//         The cached datafile is used immediately to update the SDK project config.
optimizelyManager = OptimizelyManager.builder()
                .withSDKKey("<Your_SDK_Key>")
                .withDatafileDownloadInterval(15, TimeUnit.MINUTES)
                .build(context)
optimizelyManager.initialize(context, null) { client: OptimizelyClient ->
   val user = client.createUserContext("<User_ID>")!!
   val decision = user.decide("<Flag_Key>")
}
// Here are more sample codes for synchronous and asynchronous SDK initializations with multiple options

// [Synchronous]

// [S1] Synchronous initialization
//      1. SDK is initialized instantly with a cached (or bundled) datafile
//      2. A new datafile can be downloaded in background and cached after the SDK is initialized.
//         The cached datafile will be used only when the SDK re-starts in the next session.
        
optimizelyManager =  OptimizelyManager.builder()
                .withSDKKey("<Your_SDK_Key>")
                .build(context);
optimizelyClient = optimizelyManager.initialize(context, R.raw.datafile);
user = optimizelyClient.createUserContext("<User_ID>");
decision = user.decide("<Flag_Key>");

// [S2] Synchronous initialization
//      1. SDK is initialized instantly with a cached (or bundled) datafile
//      2. A new datafile can be downloaded in background and cached after the SDK is initialized.
//         The cached datafile is used immediately to update the SDK project config.
        
optimizelyManager =  OptimizelyManager.builder()
                .withSDKKey("<Your_SDK_Key>")
                .build(context);
optimizelyClient = optimizelyManager.initialize(context, R.raw.datafile, true, true);
user = optimizelyClient.createUserContext("<User_ID>");
decision = user.decide("<Flag_Key>");

// [S3] Synchronous initialization
//      1. SDK is initialized instantly with a cached (or bundled) datafile
//      2. A new datafile can be downloaded in background and cached after the SDK is initialized.
//         The cached datafile is used immediately to update the SDK project config.
//      3. Polling datafile periodically.
//         The cached datafile is used immediately to update the SDK project config.
        
optimizelyManager =  OptimizelyManager.builder()
                .withSDKKey("<Your_SDK_Key>")
                .withDatafileDownloadInterval(15, TimeUnit.MINUTES)
                .build(context);
optimizelyClient = optimizelyManager.initialize(context, R.raw.datafile, true, true);
user = optimizelyClient.createUserContext("<User_ID>");
decision = user.decide("<Flag_Key>");

// [Asynchronous]

// [A1] Asynchronous initialization
//      1. A datafile is downloaded from the server and the SDK is initialized with the datafile
        
optimizelyManager =  OptimizelyManager.builder()
                .withSDKKey("<Your_SDK_Key>")
                .build(context);
optimizelyManager.initialize(context, null, (OptimizelyClient client) -> {
            OptimizelyUserContext userContext = client.createUserContext("<User_ID>");
            OptimizelyDecision optDecision = userContext.decide("<Flag_Key>");
});

// [A2] Asynchronous initialization
//      1. A datafile is downloaded from the server and the SDK is initialized with the datafile
//      2. Polling datafile periodically.
//         The cached datafile is used immediately to update the SDK project config.
       
optimizelyManager =  OptimizelyManager.builder()
                .withSDKKey("<Your_SDK_Key>")
                .withDatafileDownloadInterval(15, TimeUnit.MINUTES)
                .build(context);
optimizelyManager.initialize(context, null, (OptimizelyClient client) -> {
            OptimizelyUserContext userContext = client.createUserContext("<User_ID>");
            OptimizelyDecision optDecision = userContext.decide("<Flag_Key>");
});

Source files

The language and platform source files containing the implementation for Android are available on GitHub.