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绘制流程与原理详解
相关推荐
alexhilton1 天前
面向开发者的系统设计:像建筑师一样思考
android·kotlin·android jetpack
zhangmeng1 天前
FlutterBoost在iOS26真机运行崩溃问题
flutter·app·swift
CYRUS_STUDIO1 天前
用 Frida 控制 Android 线程:kill 命令、挂起与恢复全解析
android·linux·逆向
CYRUS_STUDIO1 天前
Frida 实战:Android JNI 数组 (jobjectArray) 操作全流程解析
android·逆向
大熊猫侯佩2 天前
桃花岛 Xcode 构建秘籍:Swift 中的 “Feature Flags” 心法
app·xcode·swift
LH_R2 天前
OneTerm开源堡垒机实战(三):功能扩展与效率提升
运维·后端·安全
用户092 天前
Gradle Cache Entries 深度探索
android·java·kotlin
循环不息优化不止2 天前
安卓 View 绘制机制深度解析
android
叽哥2 天前
Kotlin学习第 9 课:Kotlin 实战应用:从案例到项目
android·java·kotlin
雨白2 天前
Java 线程通信基础:interrupt、wait 和 notifyAll 详解
android·java