• SDKS
No results for ""


Android SDK reference

Read time: 10 minutes
Last edited: May 14, 2021
Supported Android SDK Versions

This library is compatible with Android SDK API versions 21 and up (5.0 Lollipop)

This reference guide documents all of the methods available in our Android SDK, and explains in detail how these methods work. If you want to dig even deeper, our SDKs are open source. To learn more, view the source on GitHub or the generated Javadocs. Additionally you can clone and run a sample application that uses this SDK.

Getting started

Building on top of our Getting Started guide, the following steps will get you started with using the LaunchDarkly SDK in your Android application.

To get started, declare a dependency on the LaunchDarkly Android SDK.

1implementation 'com.launchdarkly:launchdarkly-android-client-sdk:3.0.0'

The SDK uses AndroidX from Jetpack. For projects not currently using AndroidX, a migration guide is available here.

ProGuard / R8

If you're using ProGuard or R8, the configuration for the Android SDK should be automatically included from the aar artifact. If this is not the case for your build, include the Proguard configuration lines from consumer-proguard-rules.pro into your proguard file.

Next, import the LaunchDarkly client in your application code.

1import com.launchdarkly.sdk.*;
2import com.launchdarkly.sdk.android.*;

Once the SDK is installed, create a single, shared instance of LDClient. Specify your mobile key here so that your application is authorized to connect to LaunchDarkly and retrieve flag values for your application and environment.

The following example shows the simplest way to create the client. It will block for up to five seconds until the latest feature flags are retrieved from LaunchDarkly.

1LDConfig ldConfig = new LDConfig.Builder()
2 .mobileKey("YOUR_MOBILE_KEY")
3 .build();
5LDUser user = new LDUser.Builder("user key")
6 .email("fake@example.com")
7 .build();
9LDClient ldClient = LDClient.init(this.getApplication(), ldConfig, user, 5);
Use a mobile key

Use a mobile key from your Environments page. Never embed a server-side SDK key into an embedded or desktop application.

However, calling blocking code from the main thread in an Android app is not a best practice. The preferred method is shown below. It allows you to use the client immediately. Flags from the previous launch of the app are stored on the device and retrieved for immediate use. The client still connects in the background and continually updates itself with the latest flags.

1LDClient ldClient = LDClient.init(this.getApplication(), ldConfig, user, 0);

Using ldClient, you can check which variation a particular user receives for a given feature flag.

1boolean showFeature = ldClient.boolVariation(flagKey, true);
2if (showFeature) {
3 // application code to show the feature
5else {
6 // the code to run if the feature is off

When your application is about to terminate, shut down ldClient. This ensures that the client releases any resources it is using, and that any pending analytics events are delivered to LaunchDarkly. If your application quits without this shutdown step, you may not see your requests and users on the dashboard, because they are derived from analytics events. This is something you only need to do once.


Customizing your client

You can also pass other custom parameters to the client with the configuration object:

1LDConfig ldConfig = new LDConfig.Builder()
2 .mobileKey("YOUR_MOBILE_KEY")
3 .connectionTimeoutMillis(5000)
4 .eventsFlushIntervalMillis(5000)
5 .build();

Here, we've customized the client connect and flush interval parameters. For the full set of config options read the Javadoc.


Feature flag targeting and rollouts are determined by the user you pass to your client. The Android SDK uses a builder pattern to make it easy to construct users. Here's an example:

1LDUser user = new LDUser.Builder("aa0ceb")
2 .email("fake@example.com")
3 .firstName("Jake")
4 .lastName("Fake")
5 .custom("group", "microsoft")
6 .build();

The first argument to the builder is the user's key. This example uses the hash "aa0ceb". The user key is the only mandatory user attribute. The key should also uniquely identify each user. You can use a primary key, an email address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible.

The os and device attributes are automatically determined by the SDK and inserted into the user object. All of the other attributes (like firstName, email, and the custom attributes) are optional. The attributes you specify will automatically appear on your dashboard, meaning that you can start segmenting and targeting users with these attributes.

In addition to built-in attributes like names and email addresses, you can pass us any of your own user data by passing custom attributes, like the groups attribute in the example above.

A note on types

Most of our built-in attributes (like names and email addresses) expect string values. Custom attributes values can be strings, booleans (like true or false), numbers, or lists of strings, booleans or numbers. If you enter a custom value on our dashboard that looks like a number or a boolean, it'll be interpreted that way. The Android SDK is strongly typed, so be aware of this distinction.

Custom attributes let you target users according to any data that you send to LaunchDarkly, including organizations, groups, and account plans. Anything you pass to LaunchDarkly becomes available on your dashboard.

Private user attributes

You can optionally configure the Android SDK to treat some or all user attributes as private user attributes. Private user attributes can be used for targeting purposes, but are removed from the user data sent back to LaunchDarkly.

In the Android SDK you can define private attributes for the entire LaunchDarkly client. When creating the LDConfig object, you can call the setPrivateAttributeNames method, which which takes in a set of custom or built-in attributes as a parameter. If any user has a custom or built-in attribute named in this set, it will be removed before the user is sent to LaunchDarkly.

1LDConfig ldConfig = new LDConfig.Builder()
2 .privateAttributes(
3 UserAttribute.NAME, // built-in attribute
4 UserAttribute.forName("group") // custom attribute
5 )
6 .build();

You can also mark attributes as private when building the user object itself by using the private versions of the builder methods to set the attributes. For example:

1LDUser user = new LDUser.Builder("aa0ceb")
2 .email("fake@example.com")
3 .privateName("Jane")
4 .privateCustom("group", "microsoft")
5 .build();

When this user is sent back to LaunchDarkly, the name and group attributes will be removed.

Anonymous users

You can also distinguish logged-in users from anonymous users in the SDK, as follows:

1LDUser user = new LDUser.Builder("user key")
2 .anonymous(true)
3 .build();

You can leave the key parameter in the Builder null or make it an empty string and the client will automatically set it to a LaunchDarkly-specific device-unique string that is consistent between app restarts and device reboots. In this case, the user will also be marked as anonymous.

Anonymous users work just like regular users, except that they won't appear on your Users page in LaunchDarkly. This keeps anonymous users from polluting your Users page.

You can't search for anonymous users on your Features page, and you can't search or autocomplete by anonymous user keys.

Aliased users

There are situations in which multiple LaunchDarkly users can represent one person. For example, this can happen when a person initially logs into an application. The person might be represented by an anonymous user before they log in, and a different user after they log in. In that case, that one person would be identified by two different users as denoted by different user keys.

The SDK can associate these two LaunchDarkly users by sending an alias event.

The SDK automatically sends an alias event when identify is called with a known user if the previous user was anonymous. You can disable this behavior if necessary. To learn more, read Customizing your client.

You can manually tell the SDK to send an alias event with the alias function.

1ldClient.alias(newUser, previousUser);


The variation method determines whether a flag is enabled or not for a specific user. In Android, there is a variation method for each type (e.g. boolVariation, stringVariation):

1boolean variationResult = ldClient.boolVariation(flagKey, false);

variation calls take the feature flag key and a fallback value.

The fallback value will only be returned if an error is encountered. For example, the fallback value is served if the feature flag key doesn't exist or the user doesn't have a key specified.

Handling flag values on initial application launch

When LDClient is initialized for the first time at app launch, users will receive the feature flag fallback values until an initial connection to LaunchDarkly is completed for the first time. Take a look at the section above on various ways to initialize the client.


Since V2.7.0

The variationDetail methods (boolVariationDetail, etc.) work the same as variation, but also provide additional detailed information about how a flag value was calculated (for instance, if the user matched a specific rule). You can examine this detailed information programmatically; you can also view it with Data Export, if you are capturing detailed analytics events for this flag.

To learn more, read Evaluation reasons.

All flags

Creating users

Unlike calling the variation methods or identify, allFlags does not send events to LaunchDarkly. Retrieving a flag value using allFlags will not be recorded as an evaluation for flag evaluation metrics.

The allFlags method produces a map of feature flag keys to their values for a specific user.

1Map<String, LDValue> flagValues = ldClient.allFlags();


The track method allows you to record actions your users take in your application. Using LaunchDarkly's experimentation add-on, the dashboard allows creating metrics for the recorded actions and running experiments to gauge how metrics change depending on flag values. Here's a simple example:


You can also attach data to your event by calling trackData which should be given an LDValue parameter. This example sets the data to a JSON array, ["data", "export"], but it can be any value that can be represented in JSON; see LDValue. This data is not shown in the dashboard, but is included in supported data export destinations. To learn more, read the Data Export documentation.

1ldClient.trackData("your-event-key", LDValue.buildArray().add("data").add("export").build());

If you are using Experimentation, you can specify a numeric value with trackMetric to be used with a numeric metric.

1double metricValue = 2.5;
2ldClient.trackData("numeric-event-name", LDValue.ofNull(), metricValue);

Offline mode

In some situations, you might want to stop making remote calls to LaunchDarkly and switch to the last known values for your feature flags. offline mode lets you do this easily.

1LDConfig ldConfig = new LDConfig.Builder()
2 .mobileKey("YOUR_MOBILE_KEY")
3 .offline(true)
4 .build();
6LDClient ldClient = LDClient.init(this.getApplication(), ldConfig, user);
8// Or to switch an already-instantiated client to offline mode:
Airplane/Flight Mode

If a user's device is in airplane/flight mode or if they are not connected to a network, LaunchDarkly will use the latest stored flag settings in memory. If there are no previously stored flag settings, then the fallback values will be used.


Internally, the LaunchDarkly SDK keeps a buffer for events, such as the automatically generated events when evaluating flags or switching user contexts, as well explicit events created by calling alias or track. These are flushed periodically in a background thread. In some situations (for example, if you're testing out the SDK in a simulator), you may want to manually call flush to request any queued events to be sent immediately. Note that this call is still non-blocking, so it will return before the events are actually sent.


The flush interval is configurable. If you need to change the interval, you can do so via the configuration.

Changing the User Context

If your app is used by multiple users on a single device, you may want to change users and have separate flag settings for each user. To achieve this, the SDK will store the last 5 user contexts on a single device (configurable with LDConfig), with support for switching between different user contexts.

You can use the identify method to switch user contexts:

1LDUser updatedUser = new LDUser.Builder(user)
2 .email("fake2@example.com")
3 .build();

The identify call will load any saved flag values for the new user and immediately trigger an update of the latest flags from LaunchDarkly.

identify returns a Future to indicate completion. If you want to be sure subsequent code is using the latest values from the server, you can wait on the future using get.

Real-Time Updates

The SDK maintains what variations a user should receive locally in cache. The SDK evaluates flags based on what it has cached locally. To keep the local cache in sync with your flag configurations in LaunchDarkly, the SDK uses both a streaming strategy and a polling strategy. The SDK is highly configurable, but the default SDK configuration has low latency updates, minimal data usage, and minimal battery drain. Here is the default behavior:

  1. When the app is foregrounded a Server-Sent Events streaming connection is opened to LaunchDarkly. The initial payload from the streaming connection contains the variations your user receives. This streaming connection stays open and idles unless there are updates. This requires minimal data and battery to maintain. The streaming connection stays open as long as your app is in the foreground and is connected to the internet.
  2. When the app is backgrounded, the stream connection terminates. The SDK polls for flag updates every hour (or another interval you configure) to stay in sync. This strategy has higher latency, but optimizes battery and data usage.
  3. When the app is foregrounded, the SDK reconnects to the stream which sends the latest flag values.
  4. When streaming, the SDK actively monitors the network availability. It avoids requests when the network is unavailable, and reconnects when the network becomes available again. When polling, the SDK checks for network connectivity at the current polling interval, only making the request if the check succeeds. When it reconnects, it automatically syncs its local cache with LaunchDarkly.

This configuration means that you will get near real-time updates for your feature flag values when the app is in the foreground, and maximum efficiency when backgrounded. See the "customizing your client" section above for information on how to change your configuration.

To perform real-time updates in your app, your app will need to register listeners to be notified of changes to a flag's value when it is updated:

1String flagKey = "yourFlagKey";
3FeatureFlagChangeListener listener = new FeatureFlagChangeListener() {
4 @Override
5 public void onFeatureFlagChange(String flagKey) {
6 boolean newValue = LDClient.get().boolVariation(flagKey, false);
7 }
10LDClient.get().registerFeatureFlagListener(flagKey, listener);

The flag key passed to onFeatureFlagChange is the key of the updated flag, allowing a single listener to be registered for multiple flags.

Similarly you can unregister listeners to disable them:

1LDClient.get().unregisterFeatureFlagListener(flagKey, listener);


These calls have been available since V2.8.0:

  • LDAllFlagsListener
  • LDClient.registerAllFlagsListener
  • LDClient.unregisterAllFlagsListener

Additionally an update listener interface is provided for cases where you would like to be notified any time the flag cache is updated. The application provides a class implementing LDAllFlagsListener which provides the SDK with the method onChange. Whenever the SDK's flag cache is updated it will call the onChange method with a list of flag keys for flags that were updated during the update to the flag cache. If no flag values changed, this list will be empty.

1LDAllFlagsListener listener = new LDAllFlagsListener() {
2 @Override
3 public void onChange(List<String> flagKeys) {
4 // Get new values for flagKeys or other operations
5 }
8// register all flags listener
10// when done with all flags listener it should be unregistered

Multiple Environments

This has been available since version 2.6.0.

LaunchDarkly's Android SDK supports having multiple LDClient instances tied to separate mobile keys. This allows evaluating flags from multiple environments.

All LDClient instances will evaluate against the same LDUser. The mobile keys for additional environments are specified, along with identifying names, in a map passed to your LDConfig object.

1Map<String, String> otherKeys = new HashMap<String, String>();
2otherKeys.put("platform", "PLATFORM_MOBILE_KEY");
3otherKeys.put("core", "CORE_MOBILE_KEY");
5LDConfig ldConfig = new LDConfig.Builder()
6 .mobileKey("MOBILE_KEY")
7 .secondaryMobileKeys(otherKeys)
8 .build();
10LDUser user = new LDUser.Builder("user key")
11 .email("fake@example.com")
12 .build();
14LDClient.init(this.getApplication(), ldConfig, user);

To access the secondary mobile key instances, use the getForMobileKey method on LDClient. This method takes the identifier name assigned to your environment key in the secondaryMobileKeys map and returns the associated LDClient instance.

1LDClient coreInstance = LDClient.getForMobileKey("core");
2coreInstance.boolVariation("core-flag", false);

As all the client instances use the same LDUser object, some calls will affect all instances.

1LDClient coreInstance = LDClient.getForMobileKey("core");
3// Calls affect all LDClient Instances
4coreInstance.identify(/*User Object*/);

Track calls, listeners, and flag evaluation are all tied to the client instance they are evaluated against.

Monitoring SDK Status

This has been available since version 2.8.0

The Android SDK exposes some of its internal status through new APIs to allow your application to monitor the SDK's status. This is provided primarily as a mechanism for the application to determine how recently the internal flag cache has been updated with the most recent values, as well as diagnosing potential reasons for the flag cache to be out of date.

The SDK has seven connectivity states dependent on its configuration, application foreground state, network connectivity, as well as calls explicitly setting the client offline or online. A summary of these states is given below.

Connection ModeDescription
STREAMINGThe SDK is either connected to the flag stream, or is actively attempting to acquire a connection.
POLLINGThe SDK was configured with streaming disabled, and is in foreground polling mode.
BACKGROUND_POLLINGThe SDK has detected the application is in the background and has transitioned to battery conscious background polling.
BACKGROUND_DISABLEDThe SDK was configured with background polling disabled. The SDK has detected the application is in the background and is not attempting to update the flag cache.
OFFLINEThe SDK has detected that the mobile device does not have an active network connection so has ceased flag update attempts until the network status changes.
SET_OFFLINEThe SDK has been explicitly set offline, either in the initial configuration, by setOffline(), or as a result of failed authentication to LaunchDarkly. The SDK will stay offline unless setOnline() is called.
SHUTDOWNThe shutdown state indicates the SDK has been permanently shutdown as a result of a call to close().

The SDK also internally stores a timestamp of the most recent successful and failed connections to LaunchDarkly, as well as information related to the most recent failed connection. The LDClient method getConnectionInformation() returns a structure allowing retrieval of these fields.

1LDClient ldClient = LDClient.get();
2ConnectionInformation connectionInfo = ldClient.getConnectionInformation();
3// One of the seven modes described above
4ConnectionInformation.ConnectionMode connectionMode =
5 connectionInfo.getConnectionMode();
6// Most recent successful flag cache update in millis from the epoch
7// Or null if flags have never been retrieved
8Long lastSuccess = connectionInfo.getLastSuccessfulConnection();
9// Most recent unsuccessful flag cache update attempt in millis from the epoch
10// Or null if flag update has never been attempted
11Long lastSuccess = connectionInfo.getLastFailedConnection();
12// Most recent failure or null
13LDFailure ldFailure = connectionInfo.getLastFailure();

LDFailure is a LaunchDarklyException with an associated FailureType. It may include a .cause() propagated from an underlying exception associated with the update's failure. The cause itself should be considered unstable as it is dependent on internal implementation, though the mechanism to retrieve it will be maintained. The failure types are summarized below.

INVALID_RESPONSE_BODYA response body received either through polling or streaming was unable to be parsed.
NETWORK_FAILUREA network request for polling, or the EventSource stream reported a failure.
UNEXPECTED_STREAM_ELEMENT_TYPEAn event was received through the stream was had an unknown event name. This could indicate a newer SDK is available if new event types have become available through the flag stream since the SDKs release.
UNEXPECTED_RESPONSE_CODEThis indicates the LDFailure is an instance of LDInvalidResponseCodeFailure. See below for more details.
UNKNOWN_ERRORSome other issue occurred.

If matching on the FailureType, a default case should be used to handle any future cases provided. The UNEXPECTED_RESPONSE_CODE case indicates that the LDFailure is can be cast to a LDInvalidResponseCodeFailure for more information. This more specific failure includes a response code and whether the failure is considered retryable. An example is given below.

1LDClient ldClient = LDClient.get();
2ConnectionInformation connectionInfo = ldClient.getConnectionInformation();
3LDFailure ldFailure = connectionInfo.getLastFailure();
4if (ldFailure != null) {
5 Timber.d("Received failure with message %s", ldFailure.getMessage());
6 // Retrieve the failure type
7 LDFailure.FailureType failureType = ldFailure.getFailureType();
8 switch (failureType) {
10 Timber.d("Received invalid response body");
11 break;
13 Timber.d("Network failure, may have bad connection");
14 break;
16 Timber.d("Unexpected stream element, may require update");
17 break;
19 LDInvalidResponseCodeFailure responseCodeFailure =
20 (LDInvalidResponseCodeFailure) ldFailure;
21 int responseCode = responseCodeFailure.getResponseCode();
22 if (responseCodeFailure.isRetryable()) {
23 Timber.d("Received invalid response code %d", responseCode);
24 } else {
25 Timber.d("Received invalid response code %d, giving up", responseCode);
26 }
27 break;
29 default:
30 Timber.d("Unknown error");
31 break;
32 }
34 Throwable cause = ldFailure.getCause();
35 if (cause != null) {
36 // Do something with underlying cause
37 }

A callback based interface is also provided to allow notifying the application when the ConnectionMode changes as well as whenever the LDFailure in ConnectionStatus changes. The application must provide a class instance implementing LDStatusListener to the SDK client instance method registerStatusListener to register the listeners with the SDK. A brief example is given below.

Listener Weak Reference

The SDK maintains only a weak reference to the registered LDStatusListener, so a reference should be maintained by the application for as long as the application desires the listener to be available. This was designed to help prevent creating an inadvertent long term reference to an Activity by creating a static internal class instance for use as a listener. By using a weak reference to the listener, the Activity can still be garbage collected normally, even if it maintains a registered LDStatusListener (though unregistering the listener when finished is still recommended).

1class MainActivity extends Activity {
2 private LDClient ldClient;
3 private LDStatusListener ldStatusListener;
5 @Override
6 protected void onCreate(Bundle savedInstanceState) {
7 super.onCreate(savedInstanceState);
8 setContentView(R.layout.activity_main);
10 ldStatusListener = new LDStatusListener() {
11 @Override
12 public void onConnectionModeChanged(ConnectionInformation connectionInfo) {
13 // handle new connection info
14 }
16 @Override
17 public void onInternalFailure(LDFailure ldFailure) {
18 // handle failure
19 }
20 };
22 ldClient = LDClient.get();
23 ldClient.registerStatusListener(ldStatusListener);
24 }
26 @Override
27 protected void onDestroy() {
28 super.onDestroy();
29 ldClient.unregisterStatusListener(ldStatusListener);
30 }


The Android SDK makes heavy use of the Timber logging. Include Timber in your application to enable debug output or production logging. An example is shown below to enable debug output when the application is built with a debug configuration.

1if (BuildConfig.DEBUG) {
2 Timber.plant(new Timber.DebugTree());