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绘制流程与原理详解
相关推荐
my_power52023 分钟前
检出git项目到android studio该如何配置
android·git·android studio
JZC_xiaozhong2 小时前
多系统并行的权限治理难题:如何消除“权限孤岛”与安全风险?
安全·数据安全·etl工程师·iam·数据集成与应用集成·多系统权限管理·统一数据集成
北京聚信万通科技有限公司2 小时前
传输协议:AS3
服务器·网络·安全·电子数据交换·as3
三少爷的鞋3 小时前
Repository 方法设计:suspend 与 Flow 的决选择指南(以朋友圈为例)
android
阿里云云原生4 小时前
Android App 崩溃排查指南:阿里云 RUM 如何让你快速从告警到定位根因?
android·java
FinClip5 小时前
当券商成立互联网分公司,面向长尾客户的“智能化总攻”开始了
app
FinClip5 小时前
流量都去哪儿了?拯救APP月活,用FinClip轻松引入第三方生态
app
FinClip5 小时前
调用多个Agent,Chatkit让APP从“单打独斗”到“团队协作”
app
互亿无线明明5 小时前
国际金融短信:如何为跨境金融业务构建稳定安全的消息通知链路?
java·python·安全·eclipse·django·virtualenv·pygame
cmdch20176 小时前
手持机安卓新增推送按钮功能
android