Skip to content

Instantly share code, notes, and snippets.

@brady-aiello
Last active March 10, 2022 15:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save brady-aiello/e8dea6fdd85999575f64c1aa005ff0c1 to your computer and use it in GitHub Desktop.
Save brady-aiello/e8dea6fdd85999575f64c1aa005ff0c1 to your computer and use it in GitHub Desktop.
Setup Google One Tap with Coroutines and Activity Result Contract API
// InvalidFragmentVersionForActivityResult: https://issuetracker.google.com/issues/182388985
@SuppressLint("InvalidFragmentVersionForActivityResult")
@ExperimentalCoroutinesApi
private fun setupGoogleContinueButton() {
activity?.let { fragmentActivity ->
oneTapClient = Identity.getSignInClient(fragmentActivity)
signInRequest = createBeginSignInRequest(fragmentActivity)
val intentSender: ActivityResultLauncher<IntentSenderRequest> =
getGoogleActivityResultLauncher()
binding?.buttonContinueGoogle?.setOnClickListener {
activity?.lifecycleScope?.launchWhenStarted {
val result = beginSignInGoogleOneTap(fragmentActivity, intentSender)
oneTapLauncher.launch(
IntentSenderRequest.Builder(result.pendingIntent.intentSender)
.build()
)
}
}
}
}
private fun createBeginSignInRequest(fragmentActivity: FragmentActivity): BeginSignInRequest =
BeginSignInRequest.builder()
.setGoogleIdTokenRequestOptions(
BeginSignInRequest.GoogleIdTokenRequestOptions.builder()
.setSupported(true)
.setServerClientId(fragmentActivity.getString(R.string.server_client_id))
.setFilterByAuthorizedAccounts(false)
.build()
)
.build()
private fun getGoogleActivityResultLauncher(): ActivityResultLauncher<IntentSenderRequest> =
registerForActivityResult(StartIntentSenderForResult()) { activityResult ->
val credential: SignInCredential =
oneTapClient.getSignInCredentialFromIntent(activityResult.data)
Log.d("Credential", credential.googleIdToken.toString())
activity?.lifecycleScope?.launchWhenStarted {
loginViewModel.loginToOurServerWithGoogle(credential.googleIdToken.toString())
}
}
@ExperimentalCoroutinesApi
suspend fun beginSignInGoogleOneTap(
fragmentActivity: FragmentActivity,
oneTapClient: SignInClient,
signInRequest: BeginSignInRequest,
onCancel: () -> Unit
): BeginSignInResult =
suspendCancellableCoroutine { continuation ->
oneTapClient.beginSignIn(signInRequest)
.addOnSuccessListener(fragmentActivity) { result ->
continuation.resume(result) { throwable ->
Log.e("SignUp UI", "beginSignInGoogleOneTap: ", throwable)
}
}
.addOnFailureListener(fragmentActivity) { e ->
// No Google Accounts found. Just continue presenting the signed-out UI.
continuation.resumeWithException(e)
}
.addOnCanceledListener {
Log.d("SignUp UI", "beginSignInGoogleOneTap: cancelled")
onCancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment