Biometric authentication is the method of validating a user's identification based on unique biological appearances such as the user's retina, voice, fingerprint, or facial features, and it offers several benefits. Biometric authentication allows you to rapidly unlock your smartphone using your fingerprint or face or parttern, verifying that you are the one using it.
You must add a dependency for the AndroidX Biometric Library, which is a one-stop user authentication solution for Android developers, before you build and launch.
Step 1: Create a new project in Android Studio (File -> New -> Project -> Select Empty Activty -> Name project -> Finish)
Step 2: Insert AndroidX Biometric to build.gradle file (Module: app). (app -> build.gradle(Module: app))
implementation 'com.google.android.play:core:1.10.0'
After add this line of code in dependency section you will see top right cornor to sync link, then press that to download the library.
Step 3: In android to be able to access feature biometric we have to add permission in AndroidManifest.xml. Open app -> manifests -> AndroidManifest.xml
<uses-permission android:name="android.permission.USE_BIOMETRIC"></uses-permission>
Step 4: Add icon fingerprint for design the layout. Open app -> res -> drawable -> New -> Vector Asset
Click clip art and search for fingerprint icon. There are options to customized color, size and name you might play around with that or just leave by default then Next -> Finish.
That fingerprint icon we will use in step 5 with image for better design which is name "ic_baseline_fingerprint".
Step 5: We will design sample activity to test with both function fingerprint with PIN code input in activity_main.xml. Open app -> res -> layout -> activity_main.xml. Paste code below:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_baseline_fingerprint"
android:layout_centerInParent="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/tx_info"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login Fingerprint"
android:backgroundTint="@color/teal_700"
android:layout_centerInParent="true"
android:id="@+id/btn_fp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fingerprint + PIN"
android:layout_centerInParent="true"
android:id="@+id/btn_fppin"
/>
</androidx.appcompat.widget.LinearLayoutCompat>
Step 6: We will implement on Java class. Navigate to app - > java -> package -> MainActivity.java
package com.codebeginner.sovary.fingerprinttest;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.biometric.*;
import androidx.core.content.ContextCompat;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.Executor;
import static androidx.biometric.BiometricManager.Authenticators.*;
public class MainActivity extends AppCompatActivity {
Button btn_fp,btn_fppin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//assign button reference from view
btn_fp = findViewById(R.id.btn_fp);
btn_fppin = findViewById(R.id.btn_fppin);
//create new method to check whether support or not
checkBioMetricSupported();
}
}
Step 7: In the same class MainActivity.java we will create new method checkBioMetricSupported();
to check status fingerprint senesor so we implement it as below.
//must running android 6
void checkBioMetricSupported()
{
BiometricManager manager = BiometricManager.from(this);
String info="";
switch (manager.canAuthenticate(BIOMETRIC_WEAK | BIOMETRIC_STRONG))
{
case BiometricManager.BIOMETRIC_SUCCESS:
info = "App can authenticate using biometrics.";
enableButton(true);
break;
case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
info = "No biometric features available on this device.";
enableButton(false);
break;
case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
info = "Biometric features are currently unavailable.";
enableButton(false);
break;
case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
info = "Need register at least one finger print";
enableButton(false,true);
break;
default:
info= "Unknown cause";
enableButton(false);
}
//set message to text view so we can see what happen with sensor device
TextView txinfo = findViewById(R.id.tx_info);
txinfo.setText(info);
}
Now you will see there is no method enableButton()
implement yet, because red highlight. Okay we will create that method.
Step 8: To make more interesting application and prevent user to click button because of their sensor device is broken or something missed we disable the button with explicit method enableButton()
void enableButton(boolean enable)
{
//just enable or disable button
btn_fp.setEnabled(enable);
btn_fppin.setEnabled(true);
}
void enableButton(boolean enable,boolean enroll)
{
enableButton(enable);
if(!enroll) return;
// Prompts the user to create credentials that your app accepts.
//Open settings to set credential fingerprint or PIN
final Intent enrollIntent = new Intent(Settings.ACTION_BIOMETRIC_ENROLL);
enrollIntent.putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED,
BIOMETRIC_STRONG | DEVICE_CREDENTIAL);
startActivity(enrollIntent);
}
Step 9: After we are checking status sensor, we start perform action scan fingerprint. In onCreate()
after checkBioMetricSupported();
we start implement as below code
Executor executor = ContextCompat.getMainExecutor(this);
BiometricPrompt biometricPrompt = new BiometricPrompt(MainActivity.this,
executor, new BiometricPrompt.AuthenticationCallback() {
@Override
public void onAuthenticationError(int errorCode,
@NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
Toast.makeText(getApplicationContext(),
"Authentication error: " + errString, Toast.LENGTH_SHORT)
.show();
}
// this method will automatically call when it is succeed verify fingerprint
@Override
public void onAuthenticationSucceeded(
@NonNull BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
Toast.makeText(getApplicationContext(),
"Authentication succeeded!" , Toast.LENGTH_SHORT).show();
}
// this method will automatically call when it is failed verify fingerprint
@Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
//attempt not regconized fingerprint
Toast.makeText(getApplicationContext(), "Authentication failed",
Toast.LENGTH_SHORT)
.show();
}
});
These code above in step 8 not will happen, we will activate that code by hit buttons click action.
Step 10: Setup action buttons click to perform dialog fingerprint.
//perform action button only fingerprint
btn_fp.setOnClickListener(view -> {
// call method launch dialog fingerprint
BiometricPrompt.PromptInfo.Builder promptInfo = dialogMetric();
promptInfo.setNegativeButtonText("Cancel");
//activate callback if it succeed
biometricPrompt.authenticate(promptInfo.build());
});
//perform action button fingerprint with PIN code input
btn_fppin.setOnClickListener(view -> {
// call method launch dialog fingerprint
BiometricPrompt.PromptInfo.Builder promptInfo = dialogMetric();
promptInfo.setDeviceCredentialAllowed(true);
//activate callback if it succeed
biometricPrompt.authenticate(promptInfo.build());
});
Wait... you will see red highlight dialogMetric();
because we're not create this method yet.
Step 11: Create new method dialogMetric();
to show dialog popup to scan fingerprint.
BiometricPrompt.PromptInfo.Builder dialogMetric()
{
//Show prompt dialog
return new BiometricPrompt.PromptInfo.Builder()
.setTitle("Biometric login")
.setSubtitle("Log in using your biometric credential");
}
Alright, finally you're done look at full code below if something miss.
package com.codebeginner.sovary.fingerprinttest;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.biometric.*;
import androidx.core.content.ContextCompat;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.Executor;
import static androidx.biometric.BiometricManager.Authenticators.*;
public class MainActivity extends AppCompatActivity {
Button btn_fp,btn_fppin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//assign button reference from view
btn_fp = findViewById(R.id.btn_fp);
btn_fppin = findViewById(R.id.btn_fppin);
//create new method to check whether support or not
checkBioMetricSupported();
Executor executor = ContextCompat.getMainExecutor(this);
BiometricPrompt biometricPrompt = new BiometricPrompt(MainActivity.this,
executor, new BiometricPrompt.AuthenticationCallback() {
@Override
public void onAuthenticationError(int errorCode,
@NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
Toast.makeText(getApplicationContext(),
"Authentication error: " + errString, Toast.LENGTH_SHORT)
.show();
}
// this method will automatically call when it is succeed verify fingerprint
@Override
public void onAuthenticationSucceeded(
@NonNull BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
Toast.makeText(getApplicationContext(),
"Authentication succeeded!" , Toast.LENGTH_SHORT).show();
}
// this method will automatically call when it is failed verify fingerprint
@Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
//attempt not regconized fingerprint
Toast.makeText(getApplicationContext(), "Authentication failed",
Toast.LENGTH_SHORT)
.show();
}
});
//perform action button only fingerprint
btn_fp.setOnClickListener(view -> {
// call method launch dialog fingerprint
BiometricPrompt.PromptInfo.Builder promptInfo = dialogMetric();
promptInfo.setNegativeButtonText("Cancel");
//activate callback if it succeed
biometricPrompt.authenticate(promptInfo.build());
});
//perform action button fingerprint with PIN code input
btn_fppin.setOnClickListener(view -> {
// call method launch dialog fingerprint
BiometricPrompt.PromptInfo.Builder promptInfo = dialogMetric();
promptInfo.setDeviceCredentialAllowed(true);
//activate callback if it succeed
biometricPrompt.authenticate(promptInfo.build());
});
}
BiometricPrompt.PromptInfo.Builder dialogMetric()
{
//Show prompt dialog
return new BiometricPrompt.PromptInfo.Builder()
.setTitle("Biometric login")
.setSubtitle("Log in using your biometric credential");
}
//must running android 6
void checkBioMetricSupported()
{
BiometricManager manager = BiometricManager.from(this);
String info="";
switch (manager.canAuthenticate(BIOMETRIC_WEAK | BIOMETRIC_STRONG))
{
case BiometricManager.BIOMETRIC_SUCCESS:
info = "App can authenticate using biometrics.";
enableButton(true);
break;
case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
info = "No biometric features available on this device.";
enableButton(false);
break;
case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
info = "Biometric features are currently unavailable.";
enableButton(false);
break;
case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
info = "Need register at least one finger print";
enableButton(false,true);
break;
default:
info= "Unknown cause";
enableButton(false);
}
//set message to text view so we can see what happen with sensor device
TextView txinfo = findViewById(R.id.tx_info);
txinfo.setText(info);
}
void enableButton(boolean enable)
{
//just enable or disable button
btn_fp.setEnabled(enable);
btn_fppin.setEnabled(true);
}
void enableButton(boolean enable,boolean enroll)
{
enableButton(enable);
if(!enroll) return;
// Prompts the user to create credentials that your app accepts.
//Open settings to set credential fingerprint or PIN
final Intent enrollIntent = new Intent(Settings.ACTION_BIOMETRIC_ENROLL);
enrollIntent.putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED,
BIOMETRIC_STRONG | DEVICE_CREDENTIAL);
startActivity(enrollIntent);
}
}
Download Source Code
You might Also Like:
As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him