Skip to main content

A Jetpack Compose example app

Usage shows each verb on its own. This page puts them together in a small Jetpack Compose app: where the WiDAS instance lives, how the signed-in user's access token reaches your Broker, how status() drives the screen, and what happens when the user signs out.

It issues certificates through your Broker, the route we recommend. Copy the files, change the three constants in ExampleApplication, and plug in your own sign-in.

An example to adapt

This shows how the pieces fit together rather than being a library to drop in. Fit it to your own app's structure, and build and test it in your project before you ship it.

Prerequisites​

Set the SDK up first, exactly as the other Android pages describe. Nothing here replaces that.

  • The SDK — added to your app, with minSdk 30 or later.
  • Setup — permissions and Broker registration done, and your clientId received.
  • Your Broker — running, registered with Wi-DAS, and reachable from your app behind your own sign-in.
  • The adapter — copy MyBroker from Implement Broker into your app as it stands. The code below calls its constructor and nothing else.

What you'll build​

FileWhat it does
SignIn.ktThe small slice of your own sign-in that the example needs.
ExampleApplication.ktHolds your sign-in and builds the app's one WiDAS instance.
WiDASViewModel.ktRuns every SDK call on that instance and exposes the screen's state.
WiDASScreen.ktShows the status, serial and expiry, with Connect, Disconnect and Sign out.
MainActivity.ktHosts the screen.

All of it sits in one package, com.yourapp.widas, alongside MyBroker.

1. Dependencies​

On top of the SDK, the example uses Compose, the lifecycle libraries for ViewModel and lifecycle-aware collection, and OkHttp for MyBroker:

dependencies {
implementation(platform("androidx.compose:compose-bom:<version>"))
implementation("androidx.compose.material3:material3")
implementation("androidx.activity:activity-compose:<version>")
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:<version>") // 2.7.0 or later
implementation("androidx.lifecycle:lifecycle-runtime-compose:<version>") // 2.7.0 or later
implementation("com.squareup.okhttp3:okhttp:<version>") // used by MyBroker
}

The SDK uses OkHttp internally but doesn't expose it to your code, so declare it yourself even though the SDK already depends on it.

2. Your sign-in and the WiDAS instance​

The example needs three things from your sign-in: who the user is, a current access token, and a way to sign out. Put that behind a small interface and implement it over whatever you use today.

// SignIn.kt
package com.yourapp.widas

import android.content.Context

interface SignIn {
/** A stable ID for the signed-in user: up to 62 characters, with no `@`, spaces or control characters. */
val userId: String

/** A current access token, refreshed first if it has expired. */
suspend fun accessToken(): String

suspend fun signOut()
}

/** Your own sign-in goes here. These bodies are placeholders. */
class YourSignIn(context: Context) : SignIn {
override val userId: String get() = TODO("Replace with your own sign-in")
override suspend fun accessToken(): String = TODO("Replace with your own sign-in")
override suspend fun signOut(): Unit = TODO("Replace with your own sign-in")
}

Build one WiDAS instance for the whole app, with the brokered configure overload and the application context, and reuse it everywhere. The Application is the natural home for it, next to your sign-in. It's built the first time something asks for it.

// ExampleApplication.kt
package com.yourapp.widas

import android.app.Application
import android.content.SharedPreferences
import com.widas.sdk.WiDAS
import okhttp3.OkHttpClient

class ExampleApplication : Application() {
// Replace with your own implementation.
val signIn: SignIn by lazy { YourSignIn(this) }

// Remembers which user the certificate on this device was issued to.
val wifiPrefs: SharedPreferences by lazy { getSharedPreferences("wifi", MODE_PRIVATE) }

val widas: WiDAS by lazy {
WiDAS.configure(
context = this,
clientId = CLIENT_ID,
broker = MyBroker(
http = OkHttpClient(), // or share your app's client
endpoint = BROKER_ENDPOINT,
userAccessToken = { signIn.accessToken() }, // called on every connect()
),
baseUrl = BASE_URL,
)
}

private companion object {
const val CLIENT_ID = "client-acme"
const val BROKER_ENDPOINT = "https://api.example.com/wi-das/certificates" // your Broker
const val BASE_URL = "https://partner-api.wi-das.com/"
}
}

Register ExampleApplication as android:name on the <application> element in your manifest.

The token reaches your Broker through the lambda passed to MyBroker. Your Broker should work out who the user is from that token, not trust the user ID the app sends alongside it. The SDK calls your adapter once per connect(), and the adapter calls the lambda every time, so each request carries a freshly fetched token rather than one captured when the app started.

3. The ViewModel​

The ViewModel takes the app's WiDAS instance and your sign-in from ExampleApplication, runs every SDK call, and turns the results into state for the screen. It survives rotation, and every SDK call runs in viewModelScope, so leaving the screen for good cancels whatever is in flight. The exception is sign-out, which always runs to the end.

// WiDASViewModel.kt
package com.yourapp.widas

import android.content.SharedPreferences
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.widas.sdk.WiDAS
import com.widas.sdk.WiDASException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

data class WiDASUiState(
val status: WiDAS.Status? = null, // null until the first status() returns
val issuedToSomeoneElse: Boolean = false, // a usable certificate, but not this user's
val busy: Boolean = false,
val signingOut: Boolean = false,
val message: String? = null,
val signedOut: Boolean = false,
)

class WiDASViewModel(
private val widas: WiDAS,
private val signIn: SignIn,
private val prefs: SharedPreferences,
) : ViewModel() {

private val _state = MutableStateFlow(WiDASUiState())
val state: StateFlow<WiDASUiState> = _state.asStateFlow()

private var operation: Job? = null // the SDK operation in flight, if any
private var user: String? = null // the signed-in user, once read

// Who the certificate on this device was issued to. A certificate belongs to one user, so a
// different user signing in gets their own.
private var certificateUser: String?
get() = prefs.getString(KEY_CERTIFICATE_USER, null)
set(value) = prefs.edit().putString(KEY_CERTIFICATE_USER, value).apply()

init {
checkStatus(atLaunch = true) // onboard only if there's no usable certificate for this user
}

fun connect() = launchBusy {
signedInUser()?.let { onboard(it) }
}

/**
* Re-reads the status, and onboards again if the certificate has expired, been revoked or was
* issued to someone else.
*/
fun refresh() = checkStatus(atLaunch = false)

// Every connect() issues a new certificate, so onboard only when there's no usable one. NONE
// counts only at launch, so coming back to the foreground doesn't undo a Disconnect. VALID and
// UNKNOWN count only when the certificate was issued to someone else; otherwise UNKNOWN shows
// as unconfirmed, and the next refresh() checks again.
private fun checkStatus(atLaunch: Boolean) = launchBusy {
val user = signedInUser() // first, so readStatus() can tell whose certificate it is
val status = readStatus() ?: return@launchBusy
val onboardNow = when (status.state) {
WiDAS.Status.State.EXPIRED,
WiDAS.Status.State.REVOKED -> true
WiDAS.Status.State.NONE -> atLaunch
WiDAS.Status.State.VALID,
WiDAS.Status.State.UNKNOWN -> certificateUser != user
}
if (onboardNow && user != null) onboard(user)
}

fun disconnect() = launchBusy {
try {
widas.disconnect()
certificateUser = null
} catch (e: WiDASException) {
showError("disconnect", e)
}
readStatus()
}

/** Stops whatever is in flight, removes this user's Wi-Fi access, then signs out. */
fun signOut() {
if (_state.value.signingOut) return
_state.update { it.copy(signingOut = true, message = null) }
viewModelScope.launch {
// Finish signing out even if the user leaves the screen part-way through.
withContext(NonCancellable) {
operation?.cancelAndJoin() // its finally clears the busy flag
try {
widas.disconnect()
certificateUser = null
} catch (e: WiDASException) {
// The SDK has already forgotten the certificate, and the next connect() or
// disconnect() removes any profile left behind. Log it and carry on signing out.
Log.w(TAG, "disconnect failed during sign-out: ${e.code}", e)
}
try {
signIn.signOut()
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w(TAG, "sign-out failed", e)
readStatus() // the Wi-Fi access has gone, so show that
_state.update { it.copy(signingOut = false, message = "We couldn't sign you out. Try again.") }
return@withContext
}
_state.update { it.copy(status = null, signedOut = true) } // signingOut stays set
}
}
}

private suspend fun onboard(user: String) {
try {
retryingTransient {
widas.connect(user = user, requestedValidity = REQUESTED_VALIDITY)
}
certificateUser = user
} catch (e: WiDASException) {
showError("connect", e)
}
readStatus()
}

/** The signed-in user's ID, or null with a message if your sign-in can't say. */
private fun signedInUser(): String? =
user ?: try {
signIn.userId.also { user = it }
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w(TAG, "couldn't read the signed-in user", e)
_state.update { it.copy(message = "We couldn't confirm who's signed in. Try signing in again.") }
null
}

private suspend fun readStatus(): WiDAS.Status? =
try {
widas.status().also { status ->
val usable = status.state == WiDAS.Status.State.VALID ||
status.state == WiDAS.Status.State.UNKNOWN
val someoneElses = usable && certificateUser != user
_state.update { it.copy(status = status, issuedToSomeoneElse = someoneElses) }
}
} catch (e: WiDASException) {
// status() degrades to local state rather than failing. The one thing it
// surfaces is Internal, when the SDK can't read what it stored on the device.
showError("status", e)
null
}

/** Retries Network and ServiceUnavailable with exponential backoff, then gives up. */
private suspend fun <T> retryingTransient(block: suspend () -> T): T {
var backoffMs = INITIAL_BACKOFF_MS
repeat(MAX_ATTEMPTS - 1) {
try {
return block()
} catch (e: WiDASException) {
when (e) {
WiDASException.Network,
WiDASException.ServiceUnavailable -> Log.i(TAG, "transient ${e.code}, retrying in ${backoffMs}ms")
else -> throw e
}
}
delay(backoffMs)
backoffMs *= 2
}
return block() // the last attempt's failure goes to the caller
}

// One SDK operation at a time, and none once sign-out has started. CancellationException is
// always rethrown above, so it passes straight through here, clearing the busy flag on its way out.
private fun launchBusy(block: suspend () -> Unit) {
if (_state.value.busy || _state.value.signingOut) return
_state.update { it.copy(busy = true, message = null) }
operation = viewModelScope.launch {
try {
block()
} finally {
_state.update { it.copy(busy = false) }
}
}
}

private fun showError(action: String, e: WiDASException) {
Log.w(TAG, "$action failed: ${e.code}", e.cause ?: e)
_state.update { it.copy(message = messageFor(e)) }
}

private fun messageFor(e: WiDASException): String = when (e) {
WiDASException.Network,
WiDASException.ServiceUnavailable -> "We couldn't reach the server. Check your connection and try again."
WiDASException.EntitlementMissing -> "Wi-Fi access isn't set up for this app yet. Please contact support."
WiDASException.IssuanceRejected -> "Your Wi-Fi certificate request was refused. Please contact support."
WiDASException.PasspointInstallFailed -> "We couldn't update the Wi-Fi profile on this device. Try again."
WiDASException.Revoked -> "Your Wi-Fi access has been revoked."
is WiDASException.Internal -> "Something went wrong on this device. Please contact support."
// Play Integrity only, so never thrown on the brokered route. Give them their own
// messages if you switch to Play Integrity.
WiDASException.AttestationUnavailable,
WiDASException.AttestationRejected,
// Never thrown on Android: cancellation arrives as CancellationException instead.
WiDASException.Cancelled -> "Something went wrong. Try again."
}

companion object {
private const val TAG = "WiDASExample"

private const val REQUESTED_VALIDITY = "P365D" // ISO-8601 duration
private const val MAX_ATTEMPTS = 4
private const val INITIAL_BACKOFF_MS = 2_000L
private const val KEY_CERTIFICATE_USER = "certificateUser"

val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val app = this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as ExampleApplication
WiDASViewModel(app.widas, app.signIn, app.wifiPrefs)
}
}
}
}

A few things worth knowing:

  • Launch. When the ViewModel is created, it reads the status and onboards only for NONE, EXPIRED or REVOKED. Each connect() issues a new certificate, so it leaves a VALID one alone, and UNKNOWN shows as unconfirmed rather than issuing another. Only show this screen once the user has signed in, since connect() needs their ID and token.
  • A different user. The ViewModel remembers which user the certificate was issued to. A certificate belongs to one user, so a different user signing in on the same device gets their own: at launch or on coming back to the foreground, it onboards when it finds someone else's certificate, even a VALID or UNKNOWN one, and the screen shows it as not connected until then. The stored user starts empty, so the first launch after you ship this issues one new certificate. That's expected.
  • Expired or revoked. refresh() runs whenever the screen comes back to the foreground. If the certificate has expired or been revoked, it onboards again straight away. It leaves NONE alone, so after a Disconnect or a failed first connect(), nothing happens until the user taps Connect or the app next launches. If you revoke a user on purpose, have your Broker refuse them too; otherwise the app issues them a new certificate the next time it comes to the foreground.
  • Busy. One SDK operation runs at a time. A tap on Connect or Disconnect while something is in flight is ignored, and the screen disables those buttons to match. Retries happen inside that one operation, so the screen stays busy while it backs off.
  • Sign out. Sign out stays available while something is in flight. It cancels that operation and waits for it to stop before removing the user's access, so nobody has to sit through the retries first. Once it has started, a second tap does nothing.
  • Disconnect. The Connect button stays available afterwards. The next app launch finds NONE and connects again, so if you let users opt out of Wi-Fi access, remember that choice and don't onboard for them in init.

4. The screen​

The screen collects the state with collectAsStateWithLifecycle(), so it stops listening while the app is in the background, and asks the ViewModel to refresh each time it resumes.

// WiDASScreen.kt
package com.yourapp.widas

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.widas.sdk.WiDAS
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle

@Composable
fun WiDASScreen(
onSignedOut: () -> Unit,
viewModel: WiDASViewModel = viewModel(factory = WiDASViewModel.Factory),
) {
val state by viewModel.state.collectAsStateWithLifecycle()

LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { viewModel.refresh() }

LaunchedEffect(state.signedOut) {
if (state.signedOut) onSignedOut()
}

WiDASContent(
state = state,
onConnect = viewModel::connect,
onDisconnect = viewModel::disconnect,
onSignOut = viewModel::signOut,
)
}

@Composable
private fun WiDASContent(
state: WiDASUiState,
onConnect: () -> Unit,
onDisconnect: () -> Unit,
onSignOut: () -> Unit,
) {
val status = state.status

Column(
modifier = Modifier.fillMaxSize().padding(24.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text("Wi-Fi access", style = MaterialTheme.typography.headlineSmall)
Text(label(status, state.issuedToSomeoneElse), style = MaterialTheme.typography.titleMedium)

status?.serial?.let { Text("Certificate $it", style = MaterialTheme.typography.bodySmall) }
status?.expiry?.let { Text("Expires ${formatDate(it)}", style = MaterialTheme.typography.bodyMedium) }

state.message?.let { Text(it, color = MaterialTheme.colorScheme.error) }

if (state.busy || state.signingOut) LinearProgressIndicator(Modifier.fillMaxWidth())

val idle = !state.busy && !state.signingOut

Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
// Every connect() issues a new certificate, so it only runs when the user asks. While
// connected it's "Reinstall", which puts back a profile deleted in Settings.
val connected = status?.state == WiDAS.Status.State.VALID && !state.issuedToSomeoneElse
Button(onClick = onConnect, enabled = idle) {
Text(if (connected) "Reinstall" else "Connect")
}
OutlinedButton(
onClick = onDisconnect,
enabled = idle && status != null && status.state != WiDAS.Status.State.NONE,
) {
Text("Disconnect")
}
}

TextButton(onClick = onSignOut, enabled = !state.signingOut) {
Text("Sign out")
}
}
}

private fun label(status: WiDAS.Status?, issuedToSomeoneElse: Boolean): String =
if (issuedToSomeoneElse) "Set up for another user" else label(status)

private fun label(status: WiDAS.Status?): String = when (status?.state) {
null -> "Checking…"
WiDAS.Status.State.NONE -> "Not set up on this device"
WiDAS.Status.State.VALID -> "Connected"
WiDAS.Status.State.EXPIRED -> "Expired"
WiDAS.Status.State.REVOKED -> "Revoked"
// A certificate is installed, but nothing could confirm it's still in date.
WiDAS.Status.State.UNKNOWN -> "Set up, but we couldn't confirm it's still valid"
}

private val dateFormat: DateTimeFormatter =
DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withZone(ZoneId.systemDefault())

private fun formatDate(instant: Instant): String = dateFormat.format(instant)

UNKNOWN only happens on Android. It means a certificate was issued but neither Wi-DAS nor the device can say whether it's still in date. Show it as its own state rather than as connected; the network decides whether the device can join either way.

serial and expiry are both nullable, so the screen leaves out whichever is missing.

5. Host the screen​

// MainActivity.kt
package com.yourapp.widas

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
Surface {
WiDASScreen(
onSignedOut = {
// Go back to your sign-in screen.
finish()
},
)
}
}
}
}
}

In a larger app, WiDASScreen is one destination in your navigation graph and onSignedOut navigates to your sign-in destination instead. Pop WiDASScreen off the back stack when you do, so the next user gets a fresh ViewModel rather than the signed-out one.

Signing out​

Sign-out first cancels anything in flight, such as a connect() that's backing off, and waits for it to stop. It then calls disconnect() before your own signOut(), so the next person to use the device doesn't inherit the previous user's Wi-Fi access. If the profile won't come off, disconnect() throws PasspointInstallFailed. The SDK has already forgotten the certificate, and the next connect() or disconnect() removes any profile left behind, so the example logs it and signs out anyway. If your own signOut() fails, the screen says so and the user can try again.

Error handling​

The ViewModel sorts failures three ways:

  • Network and ServiceUnavailable are temporary. connect() tries up to four times in all, waiting 2, 4 and then 8 seconds between attempts, and shows a message only if the last attempt fails too.
  • Internal from status() means the SDK couldn't read what it stored on the device. The screen keeps the last status it had and shows a message. See status() degrades rather than throws.
  • Everything else gets a short message and is logged with its code, and its cause for Internal. None of these is worth retrying unchanged.

CancellationException is never swallowed. It isn't a WiDASException, and the two places that catch Exception rethrow it first, so when the ViewModel is cleared or sign-out cancels an operation, the work stops cleanly. See Cancellation.

Error handling has what each type means and what to fix. Log code rather than the message text, since it's stable and matches iOS.

Use Play Integrity instead​

To issue through Play Integrity, call the other configure overload in ExampleApplication: leave out broker (and with it MyBroker and the token lambda) and pass your Google Cloud project number as cloudProjectNumber, as Configure for Play Integrity instead shows. The rest of the example doesn't change, though AttestationUnavailable and AttestationRejected can then arrive and deserve their own messages. Only do this for an app that already depends on attestation, as we'll remove it in the near future.

Test on real devices

Emulators can't join a Passpoint network, so confirm onboarding on a physical device.