Enhancing app security with biometric authentication is a powerful way to provide users with a seamless and secure experience. Here's how you can implement biometric authentication in your Android app:
Steps to Implement Biometric Authentication:
-
Add Biometrics Dependency: Begin by adding the Biometric library to your
build.gradlefile inside thedependenciessection.implementation 'androidx.biometric:biometric:1.2.0-alpha03' -
Check for Biometric Hardware and Enrolled Biometrics: Before attempting to authenticate the user, check if the device supports biometric authentication and whether the user has enrolled any biometrics.
val biometricManager = BiometricManager.from(this) when (biometricManager.canAuthenticate()) { BiometricManager.BIOMETRIC_SUCCESS -> { // Biometric authentication can be used } BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> { // No biometric hardware available } BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> { // Biometric hardware currently unavailable } BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> { // Device doesn't have any biometrics enrolled } } -
Create BiometricPrompt: Use BiometricPrompt to display the authentication dialog. You'll need to create a BiometricPrompt.PromptInfo object to customize the prompt.
val executor = ContextCompat.getMainExecutor(this) val biometricPrompt = BiometricPrompt(this, executor, object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { super.onAuthenticationError(errorCode, errString) // Handle error } override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { super.onAuthenticationSucceeded(result) // Authentication succeeded, proceed with the app logic } override fun onAuthenticationFailed() { super.onAuthenticationFailed() // Handle failed authentication } }) val promptInfo = BiometricPrompt.PromptInfo.Builder() .setTitle("Biometric login for my app") .setSubtitle("Log in using your biometric credential") .setNegativeButtonText("Use account password") .build()


