目前,您可以使用 Biometric API,该 API 在后台检查设备上可用的生物识别类型(面部解锁或指纹),并将完成所有工作,包括处理许多特定于硬件的问题。
所以,从添加依赖开始:
implementation 'androidx.biometric:biometric:1.0.1'
您可以通过以下方法查看可用性:
val biometricManager = BiometricManager.from(this)
when (biometricManager.canAuthenticate()) {
BiometricManager.BIOMETRIC_SUCCESS ->
// App can authenticate using biometrics
BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE ->
// No biometric features available on this device
BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE ->
// Biometric features are currently unavailable
BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED ->
// The user hasn't associated any biometric credentials with their account
}
使用为您提供的系统对话框:
private lateinit var executor: Executor
private lateinit var biometricPrompt: BiometricPrompt
private lateinit var promptInfo: BiometricPrompt.PromptInfo
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
executor = ContextCompat.getMainExecutor(this)
biometricPrompt = BiometricPrompt(this, executor,
object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int,
errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
// Authentication error
}
override fun onAuthenticationSucceeded(
result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
// Authentication succeeded!
}
override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
// Authentication failed
}
})
promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle("Biometric login for my app")
.setSubtitle("Log in using your biometric credential")
.setNegativeButtonText("Use account password")
.build()
// Prompt appears when user clicks "Log in".
// Consider integrating with the keystore to unlock cryptographic operations,
// if needed by your app.
biometricLoginButton.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")
.setConfirmationRequired(false)
.build()
此外,您可能需要为用户设置回退以使用设备密码/密码/图案解锁。它是通过以下方式完成的:
promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle("Biometric login for my app")
.setSubtitle("Log in using your biometric credential")
// Cannot call setNegativeButtonText() and
// setDeviceCredentialAllowed() at the same time.
// .setNegativeButtonText("Use account password")
.setDeviceCredentialAllowed(true)
.build()
更多关于密码学的信息和细节可以在这里找到:https://developer.android.com/training/sign-in/biometric-auth