Class LDClient

java.lang.Object
com.launchdarkly.sdk.android.LDClient
All Implemented Interfaces:
LDClientInterface, Closeable, AutoCloseable

public class LDClient extends Object implements LDClientInterface, Closeable
Client for accessing LaunchDarkly's Feature Flag system. This class enforces a singleton pattern. The main entry point is the init(Application, LDConfig, LDContext) method.

Like all client-side LaunchDarkly SDKs, the LDClient always has a single current LDContext (evaluation context). You specify this context at initialization time, and you can change it later with identify(LDContext). All subsequent calls to evaluation methods like boolVariation(java.lang.String, boolean) refer to the flag values for the current context.

Normally, the SDK uses the exact context that you have specified in th LDContext. However, you can also tell the SDK to generate a randomized identifier and use this as the context's key; see LDConfig.Builder.generateAnonymousKeys(boolean).

  • Constructor Details

    • LDClient

      protected LDClient(@NonNull com.launchdarkly.sdk.android.PlatformState platformState, @NonNull IEnvironmentReporter environmentReporter, @NonNull com.launchdarkly.sdk.android.TaskExecutor taskExecutor, @NonNull com.launchdarkly.sdk.android.PersistentDataStoreWrapper.PerEnvironmentData environmentStore, @NonNull LDContext initialContext, @NonNull LDConfig config, @NonNull String mobileKey, @NonNull String environmentName) throws LaunchDarklyException
      Parameters:
      platformState - the platform state
      environmentReporter - the environment reporter
      taskExecutor - the task executor
      environmentStore - the environment store
      initialContext - initial context
      config - the config
      mobileKey - the mobile key
      environmentName - the environment name
      Throws:
      LaunchDarklyException - if LDClient cannot be created
  • Method Details

    • init

      public static Future<LDClient> init(@NonNull android.app.Application application, @NonNull LDConfig config, @NonNull LDContext context)
      Initializes the singleton/primary instance. The result is a Future which will complete once the client has been initialized with the latest feature flag values. For immediate access to the Client (possibly with out of date feature flags), it is safe to ignore the return value of this method, and afterward call get()

      If the client has already been initialized, is configured for offline mode, or the device is not connected to the internet, this method will return a Future that is already in the completed state.

      Parameters:
      application - your Android application
      config - configuration used to set up the client
      context - the initial evaluation context; see LDClient for more information about setting the context and optionally requesting a unique key for it
      Returns:
      a Future which will complete once the client has been initialized
      Since:
      3.0.0
      See Also:
    • init

      public static LDClient init(android.app.Application application, LDConfig config, LDContext context, int startWaitSeconds)
      Initializes the singleton instance and blocks for up to startWaitSeconds seconds until the client has been initialized. If the client does not initialize within startWaitSeconds seconds, it is returned anyway and can be used, but may not have fetched the most recent feature flag values.
      Parameters:
      application - your Android application
      config - configuration used to set up the client
      context - the initial evaluation context; see LDClient for more information about setting the context and optionally requesting a unique key for it
      startWaitSeconds - maximum number of seconds to wait for the client to initialize
      Returns:
      the primary LDClient instance
      Since:
      3.0.0
      See Also:
    • get

      public static LDClient get() throws LaunchDarklyException
      Returns the LDClient instance that was previously created with init(Application, LDConfig, LDContext, int) or init(Application, LDConfig, LDContext).

      If you have configured multiple environments, this method returns the instance for the primary environment.

      Returns:
      the singleton instance
      Throws:
      LaunchDarklyException - if init has not been called
      See Also:
    • getForMobileKey

      public static LDClient getForMobileKey(String keyName) throws LaunchDarklyException
      Returns the LDClient instance that was previously created with init(Application, LDConfig, LDContext, int) or init(Application, LDConfig, LDContext), for a specific environment.

      This method is only relevant if you have configured multiple environments with LDConfig.Builder.secondaryMobileKeys(Map).

      Parameters:
      keyName - the name you gave to this environment (this must be one of the keys in the map you passed to LDConfig.Builder.secondaryMobileKeys(Map))
      Returns:
      the singleton instance for the environment associated with the given name
      Throws:
      LaunchDarklyException - if init has not been called
      See Also:
    • trackMetric

      public void trackMetric(String eventName, LDValue data, double metricValue)
      Description copied from interface: LDClientInterface
      Tracks that an application-defined event occurred, and provides an additional numeric value for custom metrics.

      This method creates a "custom" analytics event containing the specified event name (key) the current evaluation context, optional custom data, and a numeric metric value.

      Note that event delivery is asynchronous, so the event may not actually be sent until later; see LDClientInterface.flush().

      Specified by:
      trackMetric in interface LDClientInterface
      Parameters:
      eventName - the name of the event
      data - an LDValue containing additional data associated with the event; if not applicable, you may pass either null or LDValue.ofNull()
      metricValue - a numeric value used by the LaunchDarkly experimentation feature in numeric custom metrics; this field will also be returned as part of the custom event for Data Export
      See Also:
    • trackData

      public void trackData(String eventName, LDValue data)
      Description copied from interface: LDClientInterface
      Tracks that an application-defined event occurred, and provides additional custom data.

      This method creates a "custom" analytics event containing the specified event name (key) the current evaluation context, and optional custom data. To specify a numeric metric, use LDClientInterface.trackMetric(String, LDValue, double) instead.

      Note that event delivery is asynchronous, so the event may not actually be sent until later; see LDClientInterface.flush().

      Specified by:
      trackData in interface LDClientInterface
      Parameters:
      eventName - the name of the event
      data - an LDValue containing additional data associated with the event; if not applicable, you may pass either null or LDValue.ofNull()
      See Also:
    • track

      public void track(String eventName)
      Description copied from interface: LDClientInterface
      Tracks that an application-defined event occurred.

      This method creates a "custom" analytics event containing the specified event name (key) and the current evaluation context. You may attach other data to the event by calling LDClientInterface.trackData(String, LDValue) or LDClientInterface.trackMetric(String, LDValue, double) instead.

      Note that event delivery is asynchronous, so the event may not actually be sent until later; see LDClientInterface.flush().

      Specified by:
      track in interface LDClientInterface
      Parameters:
      eventName - the name of the event
      See Also:
    • identify

      public Future<Void> identify(LDContext context)
      Description copied from interface: LDClientInterface
      Changes the current evaluation context, requests flags for that context from LaunchDarkly if we are online, and generates an analytics event to tell LaunchDarkly about the context.

      If the SDK is online, the returned Future is completed once the SDK has received feature flag values for the new context from LaunchDarkly, or received an unrecoverable error. If the SDK is offline, the returned Future is completed immediately.

      The SDK normally caches flag settings for recently used evaluation contexts; this behavior can be configured with LDConfig.Builder.maxCachedContexts(int).

      Specified by:
      identify in interface LDClientInterface
      Parameters:
      context - the new evaluation context; see LDClient for more about setting the context and optionally requesting a unique key for it
      Returns:
      a Future whose success indicates the flag values for the new evaluation context have been stored locally and are ready for use
    • allFlags

      public Map<String,LDValue> allFlags()
      Description copied from interface: LDClientInterface
      Returns a map of all feature flags for the current evaluation context. No events are sent to LaunchDarkly.
      Specified by:
      allFlags in interface LDClientInterface
      Returns:
      a map of all feature flags
    • boolVariation

      public boolean boolVariation(@NonNull String key, boolean defaultValue)
      Description copied from interface: LDClientInterface
      Returns the boolean value of a feature flag for the current evaluation context.

      If the flag variation does not have a boolean value, or if an error makes it impossible to evaluate the flag (for instance, if flagKey does not match any existing flag), defaultValue is returned.

      Specified by:
      boolVariation in interface LDClientInterface
      Parameters:
      key - key for the flag to evaluate
      defaultValue - default value in case of errors evaluating the flag
      Returns:
      value of the flag or the default value
    • boolVariationDetail

      public EvaluationDetail<Boolean> boolVariationDetail(@NonNull String key, boolean defaultValue)
      Description copied from interface: LDClientInterface
      Returns the boolean value of a feature flag for the current evaluation context, along with information about how it was calculated.

      Note that this will only work if you have set evaluationReasons to true with LDConfig.Builder.evaluationReasons(boolean). Otherwise, the reason property of the result will be null.

      The evaluation reason will also be included in analytics events, if you are capturing detailed event data for this flag.

      Specified by:
      boolVariationDetail in interface LDClientInterface
      Parameters:
      key - key for the flag to evaluate
      defaultValue - default value in case of errors evaluating the flag (see LDClientInterface.boolVariation(String, boolean))
      Returns:
      an EvaluationDetail object containing the value and other information
    • intVariation

      public int intVariation(@NonNull String key, int defaultValue)
      Description copied from interface: LDClientInterface
      Returns the integer value of a feature flag for the current evaluation context.

      If the flag variation has a numeric value that is not an integer, it is rounded toward zero.

      If the flag variation does not have a numeric value, or if an error makes it impossible to evaluate the flag (for instance, if flagKey does not match any existing flag), defaultValue is returned.

      Specified by:
      intVariation in interface LDClientInterface
      Parameters:
      key - key for the flag to evaluate
      defaultValue - default value in case of errors evaluating the flag
      Returns:
      value of the flag or the default value
    • intVariationDetail

      public EvaluationDetail<Integer> intVariationDetail(@NonNull String key, int defaultValue)
      Description copied from interface: LDClientInterface
      Returns the integer value of a feature flag for the current evaluation context, along with information about how it was calculated.

      Note that this will only work if you have set evaluationReasons to true with LDConfig.Builder.evaluationReasons(boolean). Otherwise, the reason property of the result will be null.

      The evaluation reason will also be included in analytics events, if you are capturing detailed event data for this flag.

      The behavior is otherwise identical to LDClientInterface.intVariation(java.lang.String, int).

      Specified by:
      intVariationDetail in interface LDClientInterface
      Parameters:
      key - key for the flag to evaluate
      defaultValue - default value in case of errors evaluating the flag (see LDClientInterface.intVariation(String, int))
      Returns:
      an EvaluationDetail object containing the value and other information
    • doubleVariation

      public double doubleVariation(String flagKey, double defaultValue)
      Description copied from interface: LDClientInterface
      Returns the double-precision floating-point numeric value of a feature flag for the current evaluation context.

      If the flag variation does not have a numeric value, or if an error makes it impossible to evaluate the flag (for instance, if flagKey does not match any existing flag), defaultValue is returned.

      Specified by:
      doubleVariation in interface LDClientInterface
      Parameters:
      flagKey - key for the flag to evaluate
      defaultValue - default value in case of errors evaluating the flag
      Returns:
      value of the flag or the default value
    • doubleVariationDetail

      public EvaluationDetail<Double> doubleVariationDetail(String flagKey, double defaultValue)
      Description copied from interface: LDClientInterface
      Returns the double-precision floating-point numeric value of a feature flag for the current evaluation context, along with information about how it was calculated. Note that this will only work if you have set evaluationReasons to true with LDConfig.Builder.evaluationReasons(boolean). Otherwise, the reason property of the result will be null.

      The evaluation reason will also be included in analytics events, if you are capturing detailed event data for this flag.

      The behavior is otherwise identical to LDClientInterface.doubleVariation(java.lang.String, double).

      Specified by:
      doubleVariationDetail in interface LDClientInterface
      Parameters:
      flagKey - key for the flag to evaluate
      defaultValue - default value in case of errors evaluating the flag (see LDClientInterface.doubleVariation(String, double))
      Returns:
      an EvaluationDetail object containing the value and other information.
    • stringVariation

      public String stringVariation(@NonNull String key, String defaultValue)
      Description copied from interface: LDClientInterface
      Returns the string value of a feature flag for the current evaluation context.

      If the flag variation does not have a string value, or if an error makes it impossible to evaluate the flag (for instance, if flagKey does not match any existing flag), defaultValue is returned.

      Specified by:
      stringVariation in interface LDClientInterface
      Parameters:
      key - key for the flag to evaluate
      defaultValue - default value in case of errors evaluating the flag
      Returns:
      value of the flag or the default value
    • stringVariationDetail

      public EvaluationDetail<String> stringVariationDetail(@NonNull String key, String defaultValue)
      Description copied from interface: LDClientInterface
      Returns the string value of a feature flag for the current evaluation context, along with information about how it was calculated.

      Note that this will only work if you have set evaluationReasons to true with LDConfig.Builder.evaluationReasons(boolean). Otherwise, the reason property of the result will be null.

      The evaluation reason will also be included in analytics events, if you are capturing detailed event data for this flag.

      The behavior is otherwise identical to LDClientInterface.stringVariation(java.lang.String, java.lang.String).

      Specified by:
      stringVariationDetail in interface LDClientInterface
      Parameters:
      key - key for the flag to evaluate
      defaultValue - default value in case of errors evaluating the flag (see LDClientInterface.stringVariation(String, String))
      Returns:
      an EvaluationDetail object containing the value and other information.
    • jsonValueVariation

      public LDValue jsonValueVariation(@NonNull String key, LDValue defaultValue)
      Description copied from interface: LDClientInterface
      Returns the value of a feature flag for the current evaluation context, which may be of any type.

      The type LDValue is used to represent any of the value types that can exist in JSON. Use LDValue methods to examine its type and value.

      Specified by:
      jsonValueVariation in interface LDClientInterface
      Parameters:
      key - key for the flag to evaluate
      defaultValue - default value in case of errors evaluating the flag
      Returns:
      value of the flag or the default value. Result will never be null, but may be LDValue#ofNull()
    • jsonValueVariationDetail

      public EvaluationDetail<LDValue> jsonValueVariationDetail(@NonNull String key, LDValue defaultValue)
      Description copied from interface: LDClientInterface
      Returns the value of a feature flag for the current evaluation context, which may be of any type, along with information about how it was calculated.

      The type LDValue is used to represent any of the value types that can exist in JSON. Use LDValue methods to examine its type and value.

      Note that this will only work if you have set evaluationReasons to true with LDConfig.Builder.evaluationReasons(boolean). Otherwise, the reason property of the result will be null.

      The evaluation reason will also be included in analytics events, if you are capturing detailed event data for this flag.

      The behavior is otherwise identical to LDClientInterface.jsonValueVariation(java.lang.String, com.launchdarkly.sdk.LDValue).

      Specified by:
      jsonValueVariationDetail in interface LDClientInterface
      Parameters:
      key - key for the flag to evaluate
      defaultValue - default value in case of errors evaluating the flag (see LDClientInterface.jsonValueVariation(String, LDValue))
      Returns:
      an EvaluationDetail object containing the value and other information.
    • close

      public void close() throws IOException
      Closes the client. This should only be called at the end of a client's lifecycle.
      Specified by:
      close in interface AutoCloseable
      Specified by:
      close in interface Closeable
      Throws:
      IOException - declared by the Closeable interface, but will not be thrown by the client
    • flush

      public void flush()
      Description copied from interface: LDClientInterface
      Sends all pending events to LaunchDarkly.
      Specified by:
      flush in interface LDClientInterface
    • isInitialized

      public boolean isInitialized()
      Description copied from interface: LDClientInterface
      Checks whether the client is ready to return feature flag values. This is true if either the client has successfully connected to LaunchDarkly and received feature flags, or the client has been put into offline mode (in which case it will return only default flag values).
      Specified by:
      isInitialized in interface LDClientInterface
      Returns:
      true if the client is initialized or offline
    • isOffline

      public boolean isOffline()
      Description copied from interface: LDClientInterface
      Checks whether the client has been put into offline mode. This is true only if LDClientInterface.setOffline() was called, or if the configuration had LDConfig.Builder.offline(boolean) set to true, not if the client is simply offline due to a loss of network connectivity.
      Specified by:
      isOffline in interface LDClientInterface
      Returns:
      true if the client is in offline mode
    • setOffline

      public void setOffline()
      Description copied from interface: LDClientInterface
      Shuts down any network connections maintained by the client and puts the client in offline mode, preventing the client from opening new network connections until setOnline() is called.

      Note: The client automatically monitors the device's network connectivity and app foreground status, so calling setOffline() or setOnline() is normally unnecessary in most situations.

      Specified by:
      setOffline in interface LDClientInterface
    • setOnline

      public void setOnline()
      Description copied from interface: LDClientInterface
      Restores network connectivity for the client, if the client was previously in offline mode. This operation may be throttled if it is called too frequently.

      Note: The client automatically monitors the device's network connectivity and app foreground status, so calling setOffline() or setOnline() is normally unnecessary in most situations.

      Specified by:
      setOnline in interface LDClientInterface
    • registerFeatureFlagListener

      public void registerFeatureFlagListener(String flagKey, FeatureFlagChangeListener listener)
      Description copied from interface: LDClientInterface
      Registers a FeatureFlagChangeListener to be called when the flagKey changes from its current value. If the feature flag is deleted, the listener will be unregistered.
      Specified by:
      registerFeatureFlagListener in interface LDClientInterface
      Parameters:
      flagKey - the flag key to attach the listener to
      listener - the listener to attach to the flag key
      See Also:
    • unregisterFeatureFlagListener

      public void unregisterFeatureFlagListener(String flagKey, FeatureFlagChangeListener listener)
      Description copied from interface: LDClientInterface
      Unregisters a FeatureFlagChangeListener for the flagKey.
      Specified by:
      unregisterFeatureFlagListener in interface LDClientInterface
      Parameters:
      flagKey - the flag key to remove the listener from
      listener - the listener to remove from the flag key
      See Also:
    • isDisableBackgroundPolling

      public boolean isDisableBackgroundPolling()
      Description copied from interface: LDClientInterface
      Checks whether LDConfig.Builder.disableBackgroundUpdating(boolean) was set to true in the configuration.
      Specified by:
      isDisableBackgroundPolling in interface LDClientInterface
      Returns:
      true if background polling is disabled
    • getConnectionInformation

      public ConnectionInformation getConnectionInformation()
      Description copied from interface: LDClientInterface
      Gets a ConnectionInformation object from the client representing the current state of the clients connection.
      Specified by:
      getConnectionInformation in interface LDClientInterface
      Returns:
      An object representing the status of the connection to LaunchDarkly.
    • registerStatusListener

      public void registerStatusListener(LDStatusListener statusListener)
      Description copied from interface: LDClientInterface
      Registers a LDStatusListener to be called on connection status updates.
      Specified by:
      registerStatusListener in interface LDClientInterface
      Parameters:
      statusListener - the listener to be called on a connection status update
    • unregisterStatusListener

      public void unregisterStatusListener(LDStatusListener statusListener)
      Description copied from interface: LDClientInterface
      Unregisters a LDStatusListener so it will no longer be called on connection status updates.
      Specified by:
      unregisterStatusListener in interface LDClientInterface
      Parameters:
      statusListener - the listener to be removed
    • registerAllFlagsListener

      public void registerAllFlagsListener(LDAllFlagsListener allFlagsListener)
      Description copied from interface: LDClientInterface
      Registers a LDAllFlagsListener to be called when a flag update is processed by the SDK.
      Specified by:
      registerAllFlagsListener in interface LDClientInterface
      Parameters:
      allFlagsListener - the listener to be called with a list of flag keys on a flag update
    • unregisterAllFlagsListener

      public void unregisterAllFlagsListener(LDAllFlagsListener allFlagsListener)
      Description copied from interface: LDClientInterface
      Unregisters a LDAllFlagsListener so it will no longer be called on flag updates.
      Specified by:
      unregisterAllFlagsListener in interface LDClientInterface
      Parameters:
      allFlagsListener - the listener to be removed
    • getVersion

      public String getVersion()
      Description copied from interface: LDClientInterface
      Returns the version of the SDK, for instance "2.7.0".
      Specified by:
      getVersion in interface LDClientInterface
      Returns:
      the version string