Android Biometric Authentication如何获取各认证类型及解决getAuthenticationType()失效问题
Android Biometric Authentication getAuthenticationType()无法正常工作解决方案
问题根因
你当前代码中调用了已废弃的setDeviceCredentialAllowed(true)方法开启设备凭据回退逻辑,Android原生BiometricPrompt API在该配置下getAuthenticationType()方法存在兼容性缺陷,无法正常返回Pin、图案、指纹、人脸等具体认证类型。
解决步骤
- 第一步:替换废弃API,使用
setAllowedAuthenticators()显式声明支持的认证类型,适配不同系统版本:
// 初始化PromptInfo配置 promptInfoWithPin = BiometricPrompt.PromptInfo.Builder() .setTitle("登录Android Tutorials Hub") .setSubtitle("生物认证 + 密码验证") .setDescription("使用指纹、人脸或者设备密码访问应用") .setConfirmationRequired(true) // 替换原有setDeviceCredentialAllowed(true) .setAllowedAuthenticators( if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { // API 30及以上:支持强生物认证+设备凭据 BiometricManager.Authenticators.BIOMETRIC_STRONG or BiometricManager.Authenticators.DEVICE_CREDENTIAL } else { // API 23-29兼容:支持弱生物认证+设备凭据 BiometricManager.Authenticators.BIOMETRIC_WEAK or BiometricManager.Authenticators.DEVICE_CREDENTIAL } ) .build()
- 第二步:在认证成功回调中获取准确的认证类型
val biometricPrompt = BiometricPrompt(this, mainExecutor, object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { super.onAuthenticationSucceeded(result) // 获取认证类型,API 30及以上返回值准确 when (result.authenticationType) { BiometricPrompt.AUTHENTICATION_TYPE_BIOMETRIC -> { // 指纹/人脸识别认证成功 } BiometricPrompt.AUTHENTICATION_TYPE_DEVICE_CREDENTIAL -> { // Pin/图案/密码认证成功 } } } })
- 第三步:低版本系统兼容处理
API 30以下的设备getAuthenticationType()返回值始终为-1,需额外通过BiometricManager提前检测设备生物认证状态:
val biometricManager = BiometricManager.from(this) val isBiometricEnabled = biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK) == BiometricManager.BIOMETRIC_SUCCESS // 低版本认证成功后,可通过该变量判断是生物认证还是设备凭据认证
内容的提问来源于stack exchange,提问作者kalyankumar
相关产品推荐
相关产品推荐

