Blog Infos
Author
Published
Topics
Published

Apart from making phone calls and messaging, what is the most often used feature of a smartphone? Is it photographing? Sharing files? watching videos or listening to music? It’s a function that many people utilize daily without even realizing it: biometric authentication!

Biometric identification allows you to rapidly unlock your device using your fingerprint or face, ensuring that the device is being used by you.

Note: This article requires a device with biometric authentication, such as a fingerprint scanner or an Android device with facial recognition.

I assume the reader has the basic knowledge of working with android studio or building android applications.

Getting Started

The AndroidX Biometric Library, which is a one-stop user authentication solution for Android developers, requires a dependency.

Add the following line to the end of dependencies in the app-level build.gradlefile:

dependencies {
// Java language implementation
implementation("androidx.biometric:biometric:1.1.0")
// Kotlin
implementation("androidx.biometric:biometric:1.2.0-alpha04")
}
view raw build.gradle hosted with ❤ by GitHub

You define the library version to use and include it as a compilation dependency in this code. To sync your project, go to the top-right corner of the Android Studio and click Sync Now.

The Biometric API for Android
  • Check to see if the device has biometric authentication capabilities.
  • For fingerprint or facial recognition, show a standardized biometric prompt.
  • Simple callbacks can be used to detect successful or failed authentication attempts.
  • Allow users to use their device’s PIN, pattern, or password instead of biometric credentials.

 

BiometricPrompt architecture by android Biometrics

 

Examining the Device’s Capabilities

Because of the Android Biometric APIs, not all devices support biometrics. So, first and foremost, see if your user’s device supports biometric authentication. Only a few easy steps are required.

Inside the package, create a new object file called BiometricUtil. This will be your helper class in Android Studio for managing the biometric authentication process.

Add the following function to determine the user’s hardware capability:

fun hasBiometricCapability(context: Context): Int {
val biometricManager = BiometricManager.from(context)
return biometricManager.canAuthenticate()
}

The code above builds a BiometricManager from the app context and checks whether the device supports biometric authentication with canAuthenticate().

This does not, however, imply that the user is prepared to employ biometric authentication. They may have the requisite technology for facial recognition or fingerprint reading on the device, but you may only call a BiometricPrompt if your fingerprint or face has been registered in the device’s Security Settings.

canAuthenticate() returns one of three outcomes:

  • BIOMETRIC_SUCCESS: The hardware is available and the user has enrolled their biometric data, so the device is ready to use a biometric prompt.
  • BIOMETRIC_ERROR_NONE_ENROLLED: The device has biometric capabilities, but the user has yet to enroll their fingerprints or face.
  • BIOMETRIC_ERROR_NO_HARDWARE: The device’s hardware does not support biometric authentication.

Add the following function to guarantee that the device is ready to use a biometric prompt:

fun isBiometricReady(context: Context) =
hasBiometricCapability(context) == BiometricManager.BIOMETRIC_SUCCESS

Only if the device has biometric hardware and the user has enrolled their biometrics will this return true.

Building BiometricPrompt

There’s good news if you want to use biometrics to log in and avoid having to type your password. You’re just two steps away from seeing a biometric prompt to help you log in faster.

First and foremost, you must:

  • Set PromptInfo to the message and configuration you want.
  • Use the calling activity and callback handlers to set up the biometric prompt.
Getting PromptInfo Ready

Reopen BiometricUtil.kt and add the following function:

fun setBiometricPromptInfo(
title: String,
subtitle: String,
description: String,
allowDeviceCredential: Boolean
): BiometricPrompt.PromptInfo {
val builder = BiometricPrompt.PromptInfo.Builder()
.setTitle(title)
.setSubtitle(subtitle)
.setDescription(description)
// Use Device Credentials if allowed, otherwise show Cancel Button
builder.apply {
if (allowDeviceCredential) setDeviceCredentialAllowed(true)
else setNegativeButtonText("Cancel")
}
return builder.build()
}

Job Offers

Job Offers

There are currently no vacancies.

OUR VIDEO RECOMMENDATION

, ,

Migrating to Jetpack Compose – an interop love story

Most of you are familiar with Jetpack Compose and its benefits. If you’re able to start anew and create a Compose-only app, you’re on the right track. But this talk might not be for you…
Watch Video

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer for Jetpack Compose
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engin ...
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer f ...
Google

Jobs

To generate the dialogue and populate it with the title, subtitle, and description, the code above uses a builder class called BiometricPrompt.PromptInfo.Builder.

Do you have any idea what allowDeviceCredential is for? You can set up fallback alternatives to bypass biometric authentication. When the biometric prompt appears, for example, you can choose to use the device’s existing passcode/pattern or show a Cancel button. Both alternatives are available using BiometricPrompt.PromptInfo.Builder, which includes several built-in routines.

When you set allowDeviceCredential to true, To create a specific button that launches your device’s PIN, passcode, or pattern lock screen as an additional way of user authentication, add setDeviceCredentialAllowed(true) to the dialogue builder.

allowDeviceCredential is set to false by default. A Negative or Cancel button appears on the biometric prompt in this situation. Sets the button text to Cancel with setNegativeButtonText(“Cancel”). You can, however, set any text you want, such as “Go Away.”:]

Initializing BiometricPrompt

The biometric prompt will then be initialized, and callbacks will be handled by a listener from the caller activity. The function initBiometricPrompt() does the trick. To BiometricUtil.kt, add the following code

fun initBiometricPrompt(
activity: AppCompatActivity,
listener: BiometricAuthListener
): BiometricPrompt {
// 1
val executor = ContextCompat.getMainExecutor(activity)
// 2
val callback = object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
listener.onBiometricAuthenticationError(errorCode, errString.toString())
}
override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
Log.w(this.javaClass.simpleName, "Authentication failed for an unknown reason")
}
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
listener.onBiometricAuthenticationSuccess(result)
}
}
// 3
return BiometricPrompt(activity, executor, callback)
}

The function above accomplishes three goals:

  • To handle the callback events, it constructs an executor.
  • It generates the callback object to receive authentication events with the proper result or error messages on Success, Failed, or Error state.
  • Finally, it uses the activity, executor, and callback references to create a biometric prompt. These three parameters are sent to the UI level, which displays the prompt and handles login success or failure.
Displaying BiometricPrompt

To display the biometric prompt, repeat the procedures listed above. To bind everything together, add one more function to BiometricUtil.kt:

fun showBiometricPrompt(
title: String = "Biometric Authentication",
subtitle: String = "Enter biometric credentials to proceed.",
description: String = "Input your Fingerprint or FaceID to ensure it's you!",
activity: AppCompatActivity,
listener: BiometricAuthListener,
cryptoObject: BiometricPrompt.CryptoObject? = null,
allowDeviceCredential: Boolean = false
) {
// 1
val promptInfo = setBiometricPromptInfo(
title,
subtitle,
description,
allowDeviceCredential
)
// 2
val biometricPrompt = initBiometricPrompt(activity, listener)
// 3
biometricPrompt.apply {
if (CryptoObject == null) authenticate(promptInfo)
else authenticate(promptInfo, cryptoObject)
}
}

The first two statements in this function are self-explanatory: they simply call setBiometricPromptInfo() and initBiometricPrompt() with the arguments sent in. If you don’t specify a title, subtitle, or description, PromptInfo will use the parameter defaults.

The third statement, on the other hand, is a little confusing. If CryptoObject is available, it is used in conjunction with PromptInfo to authenticate the biometric prompt.

Use the below function in your login/sign-in or in before the launch screen to use Biometrics

fun useBiometrics(view: View) {
BiometricUtil.showBiometricPrompt(
activity = this,
listener = this,
cryptoObject = null,
allowDeviceCredential = true
)
}

You can find the source code here.

GitHub – vinodbaste/android-Biometrics: Biometric identification allows you to rapidly unlock your…

 

References

Thank you for taking the time to read this article. If you found this post to be useful and interesting, please clap and recommend it.

If I got something wrong, mention it in the comments. I would love to improve.

This article was originally published on proandroiddev.com on May 09, 2022

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
It’s one of the common UX across apps to provide swipe to dismiss so…
READ MORE
blog
In this part of our series on introducing Jetpack Compose into an existing project,…
READ MORE
blog
This is the second article in an article series that will discuss the dependency…
READ MORE
blog
Let’s suppose that for some reason we are interested in doing some tests with…
READ MORE

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu