Unleash is a private, secure, and scalable feature management platform built to reduce the risk of releasing new features and accelerate software development. This Android SDK is designed to help you integrate with Unleash and use feature flags inside your application.
You can use this client with Unleash Enterprise or Unleash Open Source.
This is the Android SDK for Unleash Frontend API provided by the Unleash server or Unleash Edge. It is a lightweight SDK that allows you to connect to the Unleash Frontend API and fetch feature toggles.
This supersedes the previous Unleash Android Proxy SDK this one is a an Android library instead of a Java library.
It's not a drop-in replacement of the previous one, so it requires code changes to use it.
What are the benefits of migrating?
- Respects the Android lifecycle and stops polling and sending metrics in the background.
- Monitors network connectivity to avoid unnecessary polling (requires API level 23 or above).
- Uses the native Android logging system instead of SLF4J.
- Respects the minimum Android API level 21, but we recommend API level 23.
You will require the SDK on your classpath, so go ahead and add it to your dependency management file
implementation("io.getunleash:unleash-android:${unleash.sdk.version}")
<dependency>
<groupId>io.getunleash</groupId>
<artifactId>unleash-android</artifactId>
<version>${unleash.sdk.version}</version>
</dependency>
The minimum supported SDK level is 21, keeping in tune with OkHttp's requirement, but level 23 is recommended.
You shouldn't have to configure proguard for this library, but if you do, you can use the following configuration:
-keep class io.getunleash.android.** { *; }
Your app will need internet permission in order to reach the proxy and access network state to be able to react to network changes. So in your manifest file add
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Configure your client instance (use a single instance to avoid file contention on cache directory). For all configuration options check the UnleashConfig.Builder class.
val unleash = DefaultUnleash(
androidContext = applicationContext, // likely a reference to your Android application context
unleashConfig = UnleashConfig.newBuilder(appName = "test-android-app")
.proxyUrl("https://eu.app.unleash-hosted.com/demo/api/frontend")
.clientKey("<client-side SDK API key>")
.pollingStrategy.interval(60000)
.metricsStrategy.interval(60000)
.build()
)
// Create an initial UnleashContext
// The context can be changed at any time but we recommend you provide sensible defaults at the start
// This will make sure that the initial state for the feature toggles is correct
val initialContext = UnleashContext.newBuilder()
.userId("However you resolve your userid")
.sessionId("However you resolve your session id")
.build()
unleash.setContext(initialContext)
You can pass event listeners either when constructing DefaultUnleash or when calling start(). By default the SDK uses delayed initialization (delayedInitialization = true). When delayed initialization is enabled, any listeners you pass to the constructor are stored and only registered when you call start(). This avoids emitting events before the SDK has finished its startup sequence. If you prefer to register and activate listeners immediately, set delayedInitialization to false in the UnleashConfig and the SDK will register constructor-provided listeners at construction time and start immediately.
From the moment you call unleash.start()
, it will immediately poll for the latest feature toggles and then continue polling in the background.
Because this call is asynchronous, it will not block the main thread so you may want to check if the initial state is ready before proceeding.
You have a few options:
- Wait until Unleash is ready. This will make sure that your app is in sync with the feature toggles.
- Provide an initial state. This could make sense in cases where the network is not available and you want to provide a default state.
- None of the above. Unleash comes with a default behavior for feature toggles with unknown state.
You can check if the initial state is ready by checking unleash.isReady()
. Normally, you would add an exit condition to avoid an infinite loop.
// Start the Unleash instance
unleash.start()
// Wait until Unleash is ready
var maxWaits = 10 // 10 * 100ms = 1 seconds
while (maxWaits > 0 && !unleash.isReady()) {
// Wait until Unleash is ready
Thread.sleep(100)
maxWaits --
}
Alternatively, you can add an event listener to Unleash which is a more reactive approach. This way you can be notified when Unleash is ready:
// Start the Unleash instance
unleash.start(
eventListeners = listOf(object: UnleashReadyListener {
override fun onReady() {
// notify your app that Unleash is ready
}
})
)
If you need to have a known state for your UnleashClient, you can provide the initial state as a list of toggles. This is useful when you have a known initial state for your feature toggles.
val toggles = listOf(
Toggle(name = "flag-1", enabled = true)
)
instance.start(bootstrap = toggles)
Alternatively, you can perform a query against the frontend API using your HTTP client of choice and save the output as a json file. Then you can tell Unleash to use this file to set up toggle states.
val toggles = File("/tmp/proxyresponse.json")
unleash.start(bootstrapFile = toggles)
You can just start Unleash and it will use the default behavior for feature toggles with unknown state until it has fetched the latest state from the proxy.
In some situations this could be a valid option. For example, if you don't want the additional complexity of the option above and you are fine with the default behavior.
unleash.start()
After starting the Unleash instance, you can start using the feature toggles.
if (unleash.isEnabled("flag-1")) {
println("flag-1 enabled")
} else {
println("flag-1 disabled")
}
unleash.getVariant("flag-with-variant").let { variant ->
if (variant.featureEnabled) {
println("variant enabled: ${variant.name}") // you can also access variant.payload
} else {
println("variant disabled")
}
}
Note: to migrate from the old SDK, see the migration guide.
This SDK exposes small focused listener interfaces. Below are short copy-paste examples showing how to register them.
- Register a heartbeat listener (fires on successful fetch, 304 and errors):
val heartbeatListener = object : UnleashFetcherHeartbeatListener {
override fun togglesUpdated() {
// called when new toggles were fetched successfully
}
override fun togglesChecked() {
// called when server returns 304 Not Modified
}
override fun onError(event: HeartbeatEvent) {
// called when an error occurred while fetching
}
}
// add at start or at runtime
unleash.start(eventListeners = listOf(heartbeatListener))
// or
unleash.addUnleashEventListener(heartbeatListener)
- Register a state listener (fires when in-memory state/cache changes):
val stateListener = object : UnleashStateListener {
override fun onStateChanged() {
// called when the toggle cache was updated
}
}
unleash.addUnleashEventListener(stateListener)
- Ready listener (fires once when initial state arrives):
val readyListener = object : UnleashReadyListener {
override fun onReady() {
// initial state received — safe to proceed
}
}
unleash.addUnleashEventListener(readyListener)
You can add or remove listeners at runtime with addUnleashEventListener
/removeUnleashEventListener
.
In the sample app we use this to display the state of a toggle on the main activity. We also configured a few event listeners to display how to use them.
If you don't provide an initial state, Unleash will use the default behavior for feature toggles with unknown state. This means that if a feature toggle is not found in the list of toggles, it will be disabled by default.
The SDK uses UnleashContext as a Kotlin data class, so contexts are compared by value (all fields are compared). There are now two different fetch paths and it's important to understand which one applies in each situation:
- Scheduled polling and manual "fetch" API:
refreshTogglesWithContext
(internal fetch path) always attempts to fetch from upstream (subject to throttling and HTTP 304 handling). This is the path used by the scheduler so periodic polls will always check upstream for changes even when the context hasn't changed. - Context-change-triggered fetch:
refreshTogglesIfContextChanged
is used when the SDK is asked to update the context (setContext
/setContextWithTimeout
). That helper compares the new context to the last fetched context and will skip the network call if the values are identical.
Important details:
setContext
— when called after the SDK has started, the SDK will attempt a context-change-triggered fetch viarefreshTogglesIfContextChanged
. That helper will NOT perform a network request if the new context equals the last fetched context (prevents accidental redundant fetches when you update context with same values).setContextAsync
— updates the internal context asynchronously without forcing an immediate fetch. The scheduled polling path still runs independently and will callrefreshTogglesWithContext
periodically to check upstream for changes.refreshTogglesNow
/refreshTogglesNowAsync
— these public methods force a fetch by callingrefreshToggles
and bypass the context equality check. They still respect throttling, so excessive forced fetches may be skipped due to throttling.
- So, if you want to release 0.6.0, make a tag v0.6.0 and push it.
- To release next patch version run
./gradlew release
This is automatically handled when tags with v prefix is created in the repo. See .github/workflows/release.yml