We're building ReClaim, a minimalist Android launcher that's on Google Play. An account is optional. The account screen says so in its own copy: "ReClaim works fully without an account." If you do sign in, your settings, blocks, schedules, hidden apps and Home screen are stored with the account, so a new phone can restore them.
Adding "Continue with Google" took more care than email sign-in. A launcher runs Home as a single, self-clearing task, and that quietly broke the account picker. This post walks through what we ended up with: a small trampoline activity in its own task, a nonce that is hashed for Google and sent raw to Supabase, error codes a user can read back to us, and backup rules that keep the refresh token off Google Drive.
Stack: Kotlin, Jetpack Compose, Hilt, coroutines, androidx.credentials 1.6.0 with the googleid 1.2.1 library, and Supabase Auth reached over its REST API. minSdk is 26 and targetSdk is 36. Every snippet below is copied from the repo.
A version note first. The code below is from our repository at its current commit, where versionName is 0.6.7.3.1. The Play listing now shows 0.6.8.1.1, updated December 1, 2026, which is newer than that snapshot. Its release notes are about block screens, not sign-in, but I haven't checked the shipped sign-in flow on a device for this post, so read this as a walkthrough of the repo code.
1. The launcher's own task ate the result
A Home app's main activity is declared differently from a normal app's. Here is ReClaim's:
<activity android:name=".MainActivity" android:clearTaskOnLaunch="true" android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout|smallestScreenSize|density|uiMode|locale|layoutDirection|fontScale" android:excludeFromRecents="true" android:exported="true" android:launchMode="singleTask" android:stateNotNeeded="true" android:theme="@style/Theme.ReClaim" android:windowSoftInputMode="adjustNothing"> singleTask keeps one Home instance. clearTaskOnLaunch is the one that bit us. The <activity> docs describe it as "Whether all activities are removed from the task, except for the root activity, when it is re-launched from the home screen." For a launcher that's right: pressing Home should land on Home.
Credential Manager is called with an activity and shows its account sheet over it. In our case that activity, and the code waiting for the answer, lived in the same self-clearing task. The class comment records what happened:
/** * Home is singleTask and clears its task whenever it leaves. Credential Manager's * result lives in that task, so choosing an account was reported as a cancel and the * sign-in form stayed put. This activity runs that request in its own task. */ class GoogleSignInActivity : ComponentActivity() { Picking an account came back as a cancel, and the form just sat there. The fix was to stop asking from Home's task at all. The request now runs in a separate, invisible activity with its own task affinity:
<!-- Own task so Home's clearTaskOnLaunch does not drop the Google account choice. --> <activity android:name=".data.account.GoogleSignInActivity" android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout|smallestScreenSize|density|uiMode|locale|layoutDirection|fontScale" android:excludeFromRecents="true" android:exported="false" android:launchMode="standard" android:taskAffinity="${applicationId}.signin" android:theme="@style/Theme.ReClaim.GoogleSignIn" /> taskAffinity gives the trampoline a task of its own, so Home's task-clearing can't reach it. The task affinity docs on tasks and the back stack note that the value "must be different from the default package name", which is why it's ${applicationId}.signin and not just the package. excludeFromRecents keeps a blank entry out of the Recents screen. exported="false" means nothing outside the app can start it. The long configChanges list stops rotation or a font-size change from recreating it while the sheet is up. The theme is translucent, with no window animation and no dim, so the user should see the Google sheet over the account screen and nothing else. Its comment in themes.xml says "It must not show the wallpaper."
2. A trampoline with exactly one answer
The trampoline's lifecycle is the core of the design. It has to report exactly one result, whatever happens:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (!GoogleSignInSession.hasWaiter()) { finish() return } GoogleSignInSession.attach(this) if (savedInstanceState != null) { deliver(GoogleSignInResult.Failed(googleProblem("G10", "Sign-in screen was recreated."))) finish() return } lifecycleScope.launch { val result = try { GoogleSignIn().request(this@GoogleSignInActivity) } catch (cancelled: CancellationException) { GoogleSignInResult.Failed(googleProblem("G11", cancelled)) } deliver(result) finish() } } override fun onDestroy() { if (!delivered) { deliver(GoogleSignInResult.Failed(googleProblem("G9", "Sign-in screen closed before Google returned."))) } GoogleSignInSession.detach(this) super.onDestroy() } private fun deliver(result: GoogleSignInResult) { if (delivered) return delivered = true GoogleSignInSession.complete(result) } If nobody is waiting for a result, it finishes at once, which covers Android restoring it later with no caller around. If it's being recreated (savedInstanceState != null), it reports G10 rather than starting a second request. Otherwise it runs the real request in its own lifecycleScope. Whichever path ends first calls deliver, and the delivered flag makes every later call a no-op. onDestroy is the safety net: if the activity is torn down before Google answers, the waiting code still gets G9 instead of hanging.
The other side is a tiny process-wide handoff object. The account screen's coroutine calls await:
suspend fun await(context: Context): GoogleSignInResult { val activity = context.findActivity() ?: return GoogleSignInResult.Failed(googleProblem("G1", "No screen to open Google sign-in.")) val deferred = CompletableDeferred<GoogleSignInResult>() pending = deferred try { activity.startActivity( Intent(activity, GoogleSignInActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION), ) } catch (cancelled: CancellationException) { if (pending === deferred) pending = null throw cancelled } catch (error: Exception) { if (pending === deferred) pending = null return GoogleSignInResult.Failed(googleProblem("G12", error)) } return try { deferred.await() } finally { if (pending === deferred) { pending = null host?.finish() } } } fun complete(result: GoogleSignInResult) { val waiter = pending ?: return pending = null waiter.complete(result) } It stores a CompletableDeferred, starts the trampoline in a new task, and suspends. Two details are worth copying. First, every cleanup checks pending === deferred before clearing, so a stale call can't wipe out a newer one. Second, the finally block finishes the trampoline if the caller gives up first. Its onDestroy then tries to deliver G9, finds no waiter, and does nothing.
The object isn't synchronized. It doesn't need to be today, because the caller switches to Dispatchers.Main.immediate before calling it and the activity callbacks run on the main thread. Double taps are stopped one layer up: the account repository's manual { } wrapper uses mutex.tryLock() and returns "Wait for the current step to finish." if a step is already running.
3. One function, two roles
The public entry point is the same function for both sides. It checks which activity it was given:
internal class GoogleSignIn @Inject constructor() { suspend fun request(activityContext: Context): GoogleSignInResult { if (activityContext.findActivity() !is GoogleSignInActivity) { return GoogleSignInSession.await(activityContext) } val clientId = GoogleAuthConfig.WEB_CLIENT_ID if (clientId.isBlank()) return GoogleSignInResult.Failed(googleProblem("G2", "Web client id is missing.")) val rawNonce = ByteArray(32).also { SecureRandom().nextBytes(it) } .joinToString("") { "%02x".format(it) } val hashed = MessageDigest.getInstance("SHA-256") .digest(rawNonce.toByteArray(Charsets.UTF_8)) .joinToString("") { "%02x".format(it) } val option = GetSignInWithGoogleOption.Builder(clientId).setNonce(hashed).build() val request = GetCredentialRequest.Builder().addCredentialOption(option).build() Called from the account screen, it sees a non-trampoline activity and routes through GoogleSignInSession.await, which starts the trampoline. The trampoline then calls the same function with itself, and this time it builds the request.
GetSignInWithGoogleOption is the button-style flow. The Android guide on implementing Sign in with Google puts it as "Create a Google sign-in request with GetSignInWithGoogleOption to retrieve a Google ID Token." It fits an explicit "Continue with Google" button.
The nonce is two values
The same guide says "To prevent replay attacks, you can include a nonce for server-side verification with setNonce()." The catch is that there are two parties checking it, and they want different forms of it. Supabase's Google login guide spells it out in a code comment:
- "Use 'hashedNonce' when making the authentication request to Google"
- "Use 'nonce' when invoking the supabase.auth.signInWithIdToken() method"
So the code makes 32 bytes from SecureRandom, hex-encodes them as the raw nonce, and sends the SHA-256 of that string, also hex, to Google. Google puts the hashed value into the ID token. The raw value stays in memory and travels with the token in GoogleSignInResult.Token. Supabase gets the raw value and checks it against the hashed claim in the token. Someone who captured a token from another sign-in wouldn't have the matching raw nonce. The same Supabase guide documents a skip_nonce_check setting for the provider. We send the nonce either way, but whether the check is enforced is a dashboard setting, not something this code can see.
The rest of the request decodes the credential:
return try { val result = CredentialManager.create(activityContext).getCredential(activityContext, request) val credential = result.credential if (credential.type != GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) { return GoogleSignInResult.Failed(googleProblem("G14", credential.type)) } val token = GoogleIdTokenCredential.createFrom(credential.data).idToken if (token.isBlank()) GoogleSignInResult.Failed(googleProblem("G3", "Google returned an empty token.")) else GoogleSignInResult.Token(token, rawNonce) } catch (cancelled: CancellationException) { throw cancelled } catch (error: GetCredentialCancellationException) { GoogleSignInResult.Failed(googleProblem("G4", credentialDetail(error))) } catch (error: NoCredentialException) { GoogleSignInResult.Failed(googleProblem("G5", credentialDetail(error))) } catch (error: GetCredentialProviderConfigurationException) { GoogleSignInResult.Failed(googleProblem("G6", credentialDetail(error))) } catch (error: GetCredentialException) { GoogleSignInResult.Failed(googleProblem("G7", credentialDetail(error))) } catch (error: Exception) { GoogleSignInResult.Failed(googleProblem("G8", error)) } } The type check (G14) matters because getCredential returns a generic Credential. Only after checking for TYPE_GOOGLE_ID_TOKEN_CREDENTIAL is it safe to call GoogleIdTokenCredential.createFrom. The catch order matters too. GetCredentialCancellationException, NoCredentialException and GetCredentialProviderConfigurationException are all subclasses of GetCredentialException, so they have to come before it, or every failure would collapse into G7. Coroutine cancellation is rethrown first so the generic Exception branch can't swallow it.
4. Trading the token for a session
With an ID token and its raw nonce, the app calls Supabase Auth's token endpoint directly. There's no Supabase SDK in the Android app, just a small REST client:
suspend fun signInWithGoogle(idToken: String, nonce: String): ApiResult<AuthSession> = io { val response = request( method = "POST", path = "/auth/v1/token?grant_type=id_token", json = JSONObject() .put("provider", "google") .put("id_token", idToken) .put("nonce", nonce) .toString(), bearer = null, ) if (response.code !in 200..299) return@io ApiResult.Fail(googleServerProblem(response.body, response.code)) val json = jsonObject(response.body) ?: return@io ApiResult.Fail(googleProblem("S2", "HTTP ${response.code}")) val session = parseSession(json, "") ?: return@io ApiResult.Fail(googleProblem("S3", sessionGap(json))) ApiResult.Ok(session) } Each failure gets its own code again: S1 for a non-2xx answer, S2 when the body isn't JSON, S3 when a 2xx response is missing part of a session. The repository then runs the whole thing and stores the result exactly as email sign-in does:
/** Same account and backup as email sign-in. A failure stays on the form with a G or S code. */ suspend fun signInWithGoogle(activityContext: Context): AccountOutcome = manual { try { val google = withContext(Dispatchers.Main.immediate) { googleSignIn.request(activityContext) } when (google) { is GoogleSignInResult.Failed -> fail(google.message) is GoogleSignInResult.Token -> when (val result = api.signInWithGoogle(google.idToken, google.nonce)) { is ApiResult.Fail -> fail(result.message) is ApiResult.Ok -> { writeSession(result.value) publishSession(result.value) openAccount(result.value) } } } } catch (cancelled: CancellationException) { throw cancelled } catch (error: Exception) { fail(googleProblem("G13", error)) } } The KDoc's promise, "Same account and backup as email sign-in", is the property we cared about most. Google is just a different way to get an AuthSession. Everything after writeSession is shared code.
5. Error codes a user can read back
"It didn't work" covers a dozen different sign-in failures. So every failure message ends in a short code, and the list lives in one KDoc:
/** * Shown on the account form. G codes are the phone side. S codes are the account service. * G0 no activity from the button. G1 no activity to open the sheet. G2 missing web client id. * G3 empty token. G4 sheet cancelled. G5 no Google account. G6 Play services missing. * G7 other credential error. G8 token could not be read. G9 sheet host closed early. * G10 sheet host recreated. G11 request coroutine cancelled. G12 sheet host failed to start. * G13 unexpected error around the exchange. G14 credential was not a Google ID token. * S0 no network. S1 the account service rejected the token. S2 response was not JSON. * S3 response had no session. */ internal fun googleProblem(code: String, detail: String? = null): String { val clean = detail?.let(::googleDetail).orEmpty() return if (clean.isEmpty()) "Google sign-in didn't complete ($code)." else "Google sign-in didn't complete ($code). $clean" } A message like "Google sign-in didn't complete (G5)." tells us there was no Google account on the phone, with no logs needed. Adding the exception's own text is useful, but that text came from somewhere else and could contain anything. So googleDetail cleans it first:
internal fun googleDetail(raw: String): String { val oneLine = raw.replace(Regex("\\s+"), " ").trim() val noToken = oneLine.replace( Regex("[A-Za-z0-9_-]{12,}\\.[A-Za-z0-9_-]{12,}\\.[A-Za-z0-9_-]{8,}"), "[token]", ) return noToken.take(160) } It squashes whitespace, replaces anything shaped like a JWT (three dot-separated base64url runs) with [token], and caps the result at 160 characters. That's a cheap guard against an ID token or access token ending up in a screenshot someone posts. It's a pattern match, not a guarantee: it only catches JWT-shaped strings.
6. Keeping the refresh token out of backups
After sign-in, the session is written to SharedPreferences named reclaim_account in MODE_PRIVATE. That file holds a refresh token, which is effectively a long-lived password for the account. The app keeps android:allowBackup="true", so there are two rule files, one per backup format:
<?xml version="1.0" encoding="utf-8"?> <full-backup-content> <!-- The account session holds a refresh token. Keep it out of Android backup. --> <exclude domain="sharedpref" path="reclaim_account.xml" /> </full-backup-content> <?xml version="1.0" encoding="utf-8"?> <data-extraction-rules> <cloud-backup> <exclude domain="sharedpref" path="reclaim_account.xml" /> </cloud-backup> <device-transfer> <exclude domain="sharedpref" path="reclaim_account.xml" /> </device-transfer> </data-extraction-rules> The Auto Backup docs explain why both exist. For Android 11 and lower the fullBackupContent file is used. For "devices running Android 12 or higher, apps targeting API level 31+ use the data-extraction-rules format." In that format, a missing section is not neutral: "If there are no rules for a particular backup mode, such as if the <device-transfer> section is missing, that mode is fully enabled for all content except for no-backup and cache directories". That's why the exclude is repeated under both <cloud-backup> and <device-transfer>.
A restored phone therefore starts signed out. Signing in again fetches the account's stored setup, which is the path the account feature exists for.
The same docs describe a newer, third section, <cross-platform-transfer>, for moving data to iOS from Android 16 QPR2. ReClaim has no iOS app, so that path has nothing to match against today, and our rules don't declare it. If that ever changes, the exclude needs to go there too.
What's still open
- No tests on this path. There are no unit tests for
googleDetail, the session handoff, or the nonce, and no instrumented test for the trampoline. Everything above is from reading the code, not from a device run for this post. - No timeout.
awaitsuspends until the trampoline answers. Every path we can see ends in adeliver, but nothing bounds the wait if one doesn't. - An
Activitycrosses into a ViewModel. The account screen passes its activity into the ViewModel'scontinueWithGoogle, and the coroutine holds it for the length of the sign-in. Home'sconfigChangeslist means it isn't recreated on rotation, so it hasn't caused trouble, but it's the kind of reference that leaks if tha...

