Android Biometric API 新手使用指南

一、核心功能与使用场景

Biometric API 提供标准化的生物识别认证(指纹、人脸、虹膜等)支持,适用于以下场景:

  1. 应用登录验证

    • 替代传统密码,提升用户体验与安全性
  2. 支付/交易确认

    • 关键操作前的身份验证(如转账、修改密码)
  3. 敏感数据访问

    • 加密文件/数据库前的用户身份校验
  4. 多因素认证(MFA)​

    • 结合短信验证码、硬件密钥等增强安全性

二、基础使用示例

1. 添加依赖

gradle 复制代码
// build.gradle (app)
dependencies {
    implementation "androidx.biometric:biometric:1.1.0"
}

2. 检查设备支持情况

kotlin 复制代码
fun isBiometricAvailable(context: Context): Boolean {
    val biometricManager = BiometricManager.from(context)
    return biometricManager.canAuthenticate(
        BiometricManager.Authenticators.BIOMETRIC_STRONG
    ) == BiometricManager.BIOMETRIC_SUCCESS
}

3. 初始化 BiometricPrompt

kotlin 复制代码
private lateinit var biometricPrompt: BiometricPrompt
private lateinit var promptInfo: BiometricPrompt.PromptInfo

fun setupBiometricAuth(activity: AppCompatActivity) {
    // 初始化认证回调
    val executor = ContextCompat.getMainExecutor(activity)
    biometricPrompt = BiometricPrompt(activity, executor,
        object : BiometricPrompt.AuthenticationCallback() {
            override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                // 认证成功处理
            }

            override fun onAuthenticationFailed() {
                // 临时性失败(如指纹未识别)
            }

            override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                // 不可恢复错误(如多次失败)
            }
        })

    // 构建提示信息
    promptInfo = BiometricPrompt.PromptInfo.Builder()
        .setTitle("生物识别登录")
        .setSubtitle("请验证已有生物特征")
        .setNegativeButtonText("使用密码") // 备用验证选项
        .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)
        .build()
}

// 触发认证
fun startBiometricAuth() {
    biometricPrompt.authenticate(promptInfo)
}

三、版本兼容性处理

Android 版本 支持情况
API 23-27 使用 AndroidX Biometric 库兼容支持指纹
API 28+ 原生支持 BiometricPrompt,兼容指纹、人脸等
API 29+ 新增 BIOMETRIC_STRONGBIOMETRIC_WEAK 分级
API 30+ 要求显式声明 BIOMETRIC_* 权限

兼容代码示例

kotlin 复制代码
fun getSupportedAuthenticators(): Int {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        BiometricManager.Authenticators.BIOMETRIC_STRONG or
        BiometricManager.Authenticators.DEVICE_CREDENTIAL
    } else {
        BiometricManager.Authenticators.BIOMETRIC_STRONG
    }
}

四、注意事项与最佳实践

  1. 权限声明

    xml 复制代码
    <uses-permission android:name="android.permission.USE_BIOMETRIC" />
  2. 备用验证方式

    kotlin 复制代码
    .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG or
        BiometricManager.Authenticators.DEVICE_CREDENTIAL)
  3. 错误处理

    kotlin 复制代码
    override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
        when (errorCode) {
            BiometricPrompt.ERROR_NEGATIVE_BUTTON -> 
                // 用户选择备用验证
            BiometricPrompt.ERROR_LOCKOUT -> 
                // 认证锁定(30秒后重试)
            BiometricPrompt.ERROR_LOCKOUT_PERMANENT -> 
                // 需用户使用备用方式解锁
        }
    }
  4. 厂商定制适配

    • 华为设备 :部分旧机型需调用 HuaweiFingerprintManager
    • 三星设备 :虹膜识别需额外声明 <uses-feature android:name="com.samsung.android.sdk.iris" />
  5. 安全存储

    • 结合 AndroidKeyStore 存储加密密钥
    kotlin 复制代码
    fun generateSecretKey(): SecretKey {
        val keyGenerator = KeyGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"
        )
        keyGenerator.init(
            KeyGenParameterSpec.Builder(
                "biometric_key",
                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
            ).apply {
                setUserAuthenticationRequired(true)
                setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
            }.build()
        )
        return keyGenerator.generateKey()
    }

五、进阶功能实现

1. 加密数据绑定认证

kotlin 复制代码
val cryptoObject = BiometricPrompt.CryptoObject(cipher)
biometricPrompt.authenticate(promptInfo, cryptoObject)

2. 主动取消认证

kotlin 复制代码
fun cancelBiometricAuth() {
    biometricPrompt.cancelAuthentication()
}

3. 生物识别强度分级

kotlin 复制代码
fun checkBiometricStrength(context: Context): String {
    return when (BiometricManager.from(context).canAuthenticate(
        BiometricManager.Authenticators.BIOMETRIC_STRONG)) {
        BiometricManager.BIOMETRIC_SUCCESS -> "强生物识别"
        else -> "弱生物识别或未支持"
    }
}

六、测试与调试

  1. 模拟器测试

    • 启用虚拟指纹:Android Studio → AVD Manager → 选择设备 → 设置指纹
  2. ADB命令触发

    bash 复制代码
    adb -e emu finger touch <finger_id>
  3. 自动化测试

    kotlin 复制代码
    @Test
    fun testBiometricAuth() {
        val scenario = ActivityScenario.launch(MainActivity::class.java)
        scenario.onActivity { activity ->
            activity.startBiometricAuth()
            // 模拟认证成功
            val result = BiometricPrompt.AuthenticationResult(
                BiometricPrompt.CryptoObject(cipher))
            activity.biometricCallback.onAuthenticationSucceeded(result)
        }
    }

七、总结

  • 核心价值:平衡安全性与用户体验,降低传统密码的依赖
  • 推荐实践
    • 始终提供备用验证方式
    • 结合硬件级密钥存储(AndroidKeyStore)
    • 遵循生物识别分级策略(BIOMETRIC_STRONG/WEAK)
  • 厂商适配:针对主流厂商设备进行兼容性测试

通过合理使用 Biometric API,开发者可在保障安全性的前提下,为用户提供无缝的认证体验。

更多分享

  1. 一文吃透Kotlin中冷流(Clod Flow)和热流(Hot Flow)
  2. 一文带你吃透Kotlin协程的launch()和async()的区别
  3. 一文带你吃透接口(Interface)结合 @AutoService 与 ServiceLoader 详解
  4. 一文带你吃透Android中显示Intent与隐式Intent的区别
  5. 一文带你吃透Android View绘制流程与原理详解
相关推荐
python算法(魔法师版)38 分钟前
API安全
网络·物联网·网络协议·安全·网络安全
GIS数据转换器44 分钟前
当三维地理信息遇上气象预警:电网安全如何实现“先知先觉”?
人工智能·科技·安全·gis·智慧城市·交互
网易易盾44 分钟前
AIGC时代的内容安全:AI检测技术如何应对新型风险挑战?
人工智能·安全·aigc
w23617346011 小时前
识别安全网站,上网不再踩坑
安全
一刀到底2111 小时前
做为一个平台,给第三方提供接口的时候,除了要求让他们申请 appId 和 AppSecret 之外,还应当有哪些安全选项,要过等保3级
java·网络·安全
yxc_inspire2 小时前
基于Qt的app开发第七天
开发语言·c++·qt·app
沙振宇2 小时前
【HarmonyOS】ArkTS开发应用的横竖屏切换
android·华为·harmonyos
橙子199110164 小时前
Kotlin 中的作用域函数
android·开发语言·kotlin
zimoyin4 小时前
Kotlin 懒初始化值
android·开发语言·kotlin
枣伊吕波5 小时前
第六节第二部分:抽象类的应用-模板方法设计模式
android·java·设计模式