在 android kotlin 中使用 BiometricPrompt 解锁我的人脸识别应用程序

问题描述 投票:0回答:0

我正在使用

BiometricPrompt
来解锁我的应用程序,并在登录屏幕片段上使用面容 ID。但它在 android 版本 10、11、12 中仅显示指纹传感器。但在 android 1version 13` 中它显示指纹传感器或面部识别。但我想在所有设备上实现 Android 的最新版本。

我在 gradle 文件中使用此依赖项:-

implementation 'androidx.biometric:biometric:1.1.0'

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

//oncreate ()
showBiometricPrompt()

promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle("Face Lock")
.setDescription("Position your face within the frame.")
.setConfirmationRequired(false)
//.setNegativeButtonText("Cancel")
.setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_WEAK or     BiometricManager.Authenticators.DEVICE_CREDENTIAL)
 .setDeviceCredentialAllowed(true)
.build()

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

 override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
            // Authentication succeeded, implement your logic here
            // For face lock, you can consider this as a successful authentication
   showSuccessDialog()
 }

 override fun onAuthenticationFailed() {
            // Authentication failed, handle it if needed
            showErrorDialog()
  }

 override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
            // Authentication error, handle it if needed
            showErrorDialog()
        }
    })
}


private fun showSuccessDialog() {
    val alertDialogBuilder = AlertDialog.Builder(requireContext())
    alertDialogBuilder.setTitle("Success")
    alertDialogBuilder.setMessage("Face lock authentication successful!")
    alertDialogBuilder.setPositiveButton("OK") { dialog, _ ->
        dialog.dismiss()
        // Optionally, you can close the activity here or perform other actions.
    }

    val alertDialog = alertDialogBuilder.create()
    alertDialog.show()
}


private fun showErrorDialog() {
    val alertDialogBuilder = AlertDialog.Builder(requireContext())
    alertDialogBuilder.setTitle("Error")
    alertDialogBuilder.setMessage("Face lock authentication failed. Please try again.")
    alertDialogBuilder.setPositiveButton("OK") { dialog, _ ->
        dialog.dismiss()
        // Optionally, you can trigger another attempt at biometric authentication here.
    }

    val alertDialog = alertDialogBuilder.create()
    alertDialog.show()
}

private fun showBiometricPrompt() {
    biometricPrompt.authenticate(promptInfo)
}

请建议我如何在登录片段的应用程序代码中实现人脸识别?

android kotlin face-recognition face-detection
© www.soinside.com 2019 - 2024. All rights reserved.