androidgoogle-signincredential-manager

Google Signin on Android, Crash when clicking outside the popup


I have this very simple implementation of Google Signin

val signInWithGoogleOption =
            GetSignInWithGoogleOption.Builder("*******.apps.googleusercontent.com")
                .build()

    val request: GetCredentialRequest = GetCredentialRequest.Builder()
        .addCredentialOption(signInWithGoogleOption)
        .build()

    val credentialManager: CredentialManager = CredentialManager.create(this)

    fun test() = lifecycleScope.launch {

        val result = credentialManager.getCredential(
            request = request,
            context = this@MainActivity,
        )
        val googleIdTokenCredential = GoogleIdTokenCredential
            .createFrom(result.credential.data)

        val personToken = googleIdTokenCredential.idToken
        val personId = googleIdTokenCredential.id
        val displayName = googleIdTokenCredential.displayName
        val personPhoto = googleIdTokenCredential.profilePictureUri
    }

    try {
        test()
    } catch (f: Exception) {
        Log.e("CVE", "Exception " + f)
    }

And this is working fine, when selecting my account this is working perfectly, and I get everything I need (display name and profile picture)

But weirdly the appliocation crashes if I click outside the Google popup, or cancel:

androidx.credentials.exceptions.GetCredentialCancellationException: [16] Cancelled by user.

How can cancelling the signing make the application crash? How can I prevent that?


Solution

  • Found the issue, I had to place to try catch inside the lifecycleScope.launch

        fun test() = lifecycleScope.launch {
            try {
                val result = credentialManager.getCredential(
                    request = request,
                    context = this@MainActivity,
                )
                val googleIdTokenCredential = GoogleIdTokenCredential
                    .createFrom(result.credential.data)
        
                val personToken = googleIdTokenCredential.idToken
                val personId = googleIdTokenCredential.id
                val displayName = googleIdTokenCredential.displayName
                val personPhoto = googleIdTokenCredential.profilePictureUri
           } catch (f: Exception) {
                Log.e("CVE", "Exception " + f)
           }
        }