Skip to content

Instantly share code, notes, and snippets.

@juancruzgs
Last active April 11, 2021 15:00
Show Gist options
  • Save juancruzgs/b38700fd3c78d4552b0241a3ad4bdeb2 to your computer and use it in GitHub Desktop.
Save juancruzgs/b38700fd3c78d4552b0241a3ad4bdeb2 to your computer and use it in GitHub Desktop.
BiometricsPrompt full implementation
class BiometricsManagerImpl : BiometricsManager {
private val executor = MainThreadExecutor()
override fun authenticate(activity: FragmentActivity): Completable {
return Completable.create { emitter ->
val prompt = BiometricPrompt(
activity,
executor,
object : BiometricPrompt.AuthenticationCallback() {
@SuppressLint("SwitchIntDef")
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
val exception = when (errorCode) {
BiometricConstants.ERROR_HW_NOT_PRESENT,
BiometricConstants.ERROR_HW_UNAVAILABLE,
BiometricConstants.ERROR_NO_BIOMETRICS ->
BiometricsNotAvailableException("Code: $errorCode, Message: $errString")
else -> BiometricCancelledException("Code: $errorCode, Message: $errString")
}
emitter.onError(exception)
}
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
emitter.onComplete()
}
})
val promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle(activity.getString(R.string.biometric_authentication_title))
.setDescription(activity.getString(R.string.biometric_authentication_description))
.setNegativeButtonText(activity.getString(R.string.global_cancel))
.build()
prompt.authenticate(promptInfo)
}
}
inner class MainThreadExecutor : Executor {
private val handler = Handler(Looper.getMainLooper())
override fun execute(runnable: Runnable) {
handler.post(runnable)
}
}
}
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
class BiometricCancelledException(message: String? = null) : Exception(message)
interface BiometricsManager {
fun authenticate(activity: FragmentActivity): Completable
}
class BiometricsNotAvailableException(message: String? = null) : Exception(message)
//Biometrics Prompt
implementation 'androidx.biometric:biometric:1.0.0-alpha03'
//Reactive programming
implementation "io.reactivex.rxjava2:rxkotlin:2.3.0"
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val biometricsManager: BiometricsManager = BiometricsManagerImpl()
biometricsManager.authenticate(this)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
// Authentication Succeeded
}, { exception ->
when (exception) {
is BiometricsNotAvailableException -> {
// Biometrics not available
}
is BiometricCancelledException -> {
// User error
}
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment