如何使用BiometricManager或BiometricPrompt检查生物识别硬件是否可用?

时间:2019-08-30 13:19:59

标签: java android kotlin android-fingerprint-api android-biometric-prompt

我正在使用BiometricPrompt类实现生物识别身份验证。

  1. 在调用BiometricPrompt#authenticate方法之前如何检查硬件是否可用?
  2. 如何检查已注册的生物识别技术?

如何调用BiometricManager#canAuthenticate方法? 我无法在Kotlin中为BiometricManager类创建对象

我当前的实现如下。

    val executor = Executors.newSingleThreadExecutor()

    val biometricPrompt = BiometricPrompt(this, executor, object : BiometricPrompt.AuthenticationCallback() {

        override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
            super.onAuthenticationError(errorCode, errString)
            Log.d("BIOMETRIC", "$errString $errorCode")

            if (BiometricPrompt.ERROR_HW_NOT_PRESENT == errorCode || BiometricPrompt.ERROR_NO_BIOMETRICS == errorCode)
                PreferenceHandler.setBiometricAvailable(this@LockActivity, false)
            else
                PreferenceHandler.setBiometricAvailable(this@LockActivity, true)
        }

        override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
            super.onAuthenticationSucceeded(result)
        }

        override fun onAuthenticationFailed() {
            super.onAuthenticationFailed()
            Log.d("BIOMETRIC", "FAILED")
        }
    })

    val promptInfo = BiometricPrompt.PromptInfo.Builder()
            .setTitle("App title")
            .setSubtitle("")
            .setDescription("Identify yourself by Biometrics")
            .setNegativeButtonText("Use Password")
            .build()

    biometricPrompt.authenticate(promptInfo)

1 个答案:

答案 0 :(得分:2)

最终已解决

BiometricManager类在androidx库中丢失

androidx.biometric:biometric:1.0.0-alpha04

将库版本更新为

androidx.biometric:biometric:1.0.0-beta01

现在您可以导入androidx.biometric.BiometricManager

您可以检查生物识别硬件的可用性,并通过以下代码注册生物识别:

object BiometricUtil {

fun isHardwareAvailable(context: Context): Boolean{
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        val bm = BiometricManager.from(context)
        val canAuthenticate = bm.canAuthenticate()
        !(canAuthenticate == BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE || canAuthenticate == BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE)

    } else {
        false
    }
}

fun hasBiometricEnrolled(context: Context): Boolean {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        val bm = BiometricManager.from(context)
        val canAuthenticate = bm.canAuthenticate()
        (canAuthenticate == BiometricManager.BIOMETRIC_SUCCESS)

    } else {
        false
    }
}
}