Skip to content

Biometric 生物识别

源:生物识别认证指南

Biometric 库提供了一套统一的对话框和流程,用于在 Android 应用中安全地处理指纹、面容和虹膜等生物识别认证。

1. 添加依赖

kotlin
[versions]
biometric = "1.1.0"

[libraries]
androidx-biometric = { group = "androidx.biometric", name = "biometric", version.ref = "biometric" }
kotlin
dependencies {
    implementation(libs.androidx.biometric)
}

2. 核心步骤

第一步:检查认证能力

在提示用户认证前,先检查硬件是否支持且用户是否已录入生物特征。

kotlin
val biometricManager = BiometricManager.from(this)
when (biometricManager.canAuthenticate(BIOMETRIC_STRONG or DEVICE_CREDENTIAL)) {
    BiometricManager.BIOMETRIC_SUCCESS ->
        Log.d("MY_APP_TAG", "应用可以使用生物识别进行认证。")
    BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE ->
        Log.e("MY_APP_TAG", "此设备上没有生物识别功能。")
    BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE ->
        Log.e("MY_APP_TAG", "生物识别功能当前不可用。")
    BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED ->
        Log.e("MY_APP_TAG", "用户未录入生物识别特征。")
}

第二步:创建认证对话框

kotlin
private lateinit var executor: Executor
private lateinit var biometricPrompt: BiometricPrompt
private lateinit var promptInfo: BiometricPrompt.PromptInfo

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    executor = ContextCompat.getMainExecutor(this)
    
    biometricPrompt = BiometricPrompt(this, executor,
        object : BiometricPrompt.AuthenticationCallback() {
            override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                super.onAuthenticationSucceeded(result)
                Toast.makeText(applicationContext, "认证成功!", Toast.LENGTH_SHORT).show()
            }

            override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                super.onAuthenticationError(errorCode, errString)
                Toast.makeText(applicationContext, "认证错误: \$errString", Toast.LENGTH_SHORT).show()
            }
        })

    promptInfo = BiometricPrompt.PromptInfo.Builder()
        .setTitle("生物识别登录")
        .setSubtitle("使用您的指纹或面容登录应用")
        .setNegativeButtonText("使用账号密码登录")
        .build()
}

第三步:触发认证

kotlin
biometricButton.setOnClickListener {
    biometricPrompt.authenticate(promptInfo)
}

3. 认证级别

  • BIOMETRIC_STRONG: 满足 Class 3 级别的安全性(最高级)。
  • BIOMETRIC_WEAK: 满足 Class 2 级别的安全性。
  • DEVICE_CREDENTIAL: 允许使用 PIN 码、图案或密码作为备选。

注意

如果指定了 DEVICE_CREDENTIAL,则不能同时调用 setNegativeButtonText(),因为系统会自动处理回退逻辑。