The Coder
The Coder

Reputation: 1

Biometric Authentication in Jetpack Compose with ComponentActivity?

I'm try to add bio metric authentication to my app with BiometricPrompt, but when i call the function the app crashes logging MainActivity cannot access to Fragment Activity so i changed the Component Activity in MainActivity to FragmentActivity and it worked so should i stick to FragmentActivity or is there any other way?

Here is my prompt function

fun showBiometricPrompt(context: Context, onAuthResult: (String) -> Unit) {
 val activity = context as FragmentActivity val biometricManager = BiometricManager.from(context)when (biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG)) {
    BiometricManager.BIOMETRIC_SUCCESS -> {
        val executor = ContextCompat.getMainExecutor(context)
        val biometricPrompt = BiometricPrompt(
            activity,
            executor,
            object : BiometricPrompt.AuthenticationCallback() {
                override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                    super.onAuthenticationSucceeded(result)
                    onAuthResult("success")
                }

                override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                    super.onAuthenticationError(errorCode, errString)
                    onAuthResult("error")
                }

                override fun onAuthenticationFailed() {
                    super.onAuthenticationFailed()
                    onAuthResult("failed")
                }
            }
        )

        val promptInfo = BiometricPrompt.PromptInfo.Builder()
            .setTitle("Biometric Auth")
            .setSubtitle("Please verify your identity")
            .setNegativeButtonText("Cancel")
            .build()

        biometricPrompt.authenticate(promptInfo)
    }
    else -> {
        showAlert(context, "Biometric authentication not supported")
    }
}
}

And this is MainActivity.kt

Before

class MainActivity : ComponentActivity() {}

After

class MainActivity : FragmentActivity() {}

Upvotes: 0

Views: 23

Answers (0)

Related Questions