从API 29 即 Android 10 开始,系统为第三方应用提供了通过生物识别验证用户是否为本人的功能,实现也比较简单
首先要使用生物识别需要判断系统版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
}else{
}
声明权限
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
创建对象 整个流程基本涉及三个对象 BiometricPrompt为生物识别的对话框,通过Builder的build()方法创建,通过authenticate方法显示 CancellationSignal为主动取消生物识别的标识,在需要主动取消生物识别(关闭对话框)的时候,需要调用CancellationSignal的cancel()方法。重复显示对话框时不能复用同一个CancellationSignal,否则会抛出异常 AuthenticationCallback是验证结果的回调,包括验证成功、失败、取消等
biometricPrompt=BiometricPrompt.Builder(this)
.setTitle("生物识别标题")
.setDescription("描述")
.setNegativeButton("取消",mainExecutor, object : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
Toast.makeText(this@MainActivity, "取消", Toast.LENGTH_SHORT).show()
}
})
.build()
authenticationCallback=object : BiometricPrompt.AuthenticationCallback(){
override fun onAuthenticationError(errorCode: Int, errString: CharSequence?) {
super.onAuthenticationError(errorCode, errString)
Log.i(TAG, "onAuthenticationError: ${errString}")
}
override fun onAuthenticationHelp(helpCode: Int, helpString: CharSequence?) {
super.onAuthenticationHelp(helpCode, helpString)
Log.i(TAG, "onAuthenticationHelp: ${helpString}")
}
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult?) {
super.onAuthenticationSucceeded(result)
Log.i(TAG, "onAuthenticationSucceeded: ")
}
override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
Log.i(TAG, "onAuthenticationFailed: ")
}
}
开始验证
cancellationSignal= CancellationSignal()
cancellationSignal.setOnCancelListener {
}
biometricPrompt.authenticate(cancellationSignal,mainExecutor,authenticationCallback)
|