Kotlin Biometrics Or Fingerprint Example

Kotlin Biometrics or Fingerprint Example

Step 1:
Open build.gradle(:app) and add following dependency and rebuild the project.
implementation 'androidx.biometric:biometric:1.2.0-alpha04'
build.gradle(:app)
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}

android {
compileSdk 32

defaultConfig {
applicationId "com.kotlinkattademo.app"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
dataBinding true;
viewBinding true
}
}

dependencies {

implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

implementation 'androidx.biometric:biometric:1.2.0-alpha04'
}
Step 2:
Open AndroidManifest.xml and add following permission.
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
Step 3:
Open layout file activity_main.xml and add following code.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
tools:context=".MainActivity">

<androidx.appcompat.widget.AppCompatButton
android:background="@color/black"
android:textColor="@color/white"
android:textSize="22dp"
android:id="@+id/biometriclogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Biometric login"
android:textAllCaps="false"
android:layout_margin="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
Step 4:
Open Activity class MainActivity.kt and add following code.
package com.kotlinkattademo.app

import android.content.ActivityNotFoundException
import android.content.DialogInterface
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.provider.Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.biometric.BiometricPrompt
import androidx.core.content.ContextCompat
import com.kotlinkattademo.app.databinding.ActivityMainBinding
import java.util.concurrent.Executor

class MainActivity : AppCompatActivity() {

private lateinit var executor: Executor
private lateinit var biometricPrompt: BiometricPrompt
private lateinit var promptInfo: BiometricPrompt.PromptInfo

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)

binding.biometriclogin.setOnClickListener {
biometricPrompt.authenticate(promptInfo)
}

promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle("Biometric login for my app")
.setSubtitle("Log in using your biometric credential")
.setNegativeButtonText("Use account password")
.build()

executor = ContextCompat.getMainExecutor(this)
biometricPrompt = BiometricPrompt(this, executor,
object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(
errorCode: Int,
errString: CharSequence
) {
super.onAuthenticationError(errorCode, errString)
Toast.makeText(
applicationContext,
"Authentication error: $errString",
Toast.LENGTH_SHORT
).show()

biomatricAlert()
}

override fun onAuthenticationSucceeded(
result: BiometricPrompt.AuthenticationResult
) {
super.onAuthenticationSucceeded(result)
Toast.makeText(
applicationContext,
"Authentication succeeded!",
Toast.LENGTH_SHORT
).show()
}

override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
Toast.makeText(applicationContext, "Authentication failed", Toast.LENGTH_SHORT)
.show()
}
})
}

private fun launchIntentToAddBiomatric() {
val intent: Intent = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
Intent(Settings.ACTION_BIOMETRIC_ENROLL).putExtra(
EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED,
android.hardware.biometrics.BiometricManager.Authenticators.BIOMETRIC_STRONG
)
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P -> {
Intent(Settings.ACTION_FINGERPRINT_ENROLL)
}
else -> {
Intent(Settings.ACTION_SECURITY_SETTINGS)
}
}
try {
startActivity(intent)
} catch (error: ActivityNotFoundException) {
startActivity(Intent(Settings.ACTION_SETTINGS))
}
}

fun biomatricAlert() {
val builder = AlertDialog.Builder(this)
with(builder)
{
setTitle("Add Biomatric")
setMessage("would you like to add biomatric?")
setPositiveButton(
"Next",
DialogInterface.OnClickListener(positiveButtonClick)
)
setNegativeButton("Close", negativeButtonClick)
show()
}
}

val positiveButtonClick = { dialog: DialogInterface, which: Int ->
dialog.dismiss()
launchIntentToAddBiomatric() // launch Intent to open add Biomatric.
}
val negativeButtonClick = { dialog: DialogInterface, which: Int ->
dialog.dismiss();
}
}
Output:

Comments