如果您在Activity中创建biometricPrompt和promptInfo,则可以正常工作。但是我无法使其在Fragment内部工作。
这是在Fragment内部,并且在OnViewCreated中被调用。如果您在Activity内部执行相同的操作,则会很好地工作,一种解决方法是从Activity传递biometricPrompt和PromptInfo,并将其传递到Fragment内部。
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
tryToDisplayBiometricPrompt()
}
@TargetApi(Build.VERSION_CODES.M)
private fun tryToDisplayBiometricPrompt() {
//Create a thread pool with a single thread
biometricPrompt = BiometricPrompt(activity as FragmentActivity, Executors.newSingleThreadExecutor(), object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
authenticationSuccessful()
}
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
if (errorCode == BiometricConstants.ERROR_NEGATIVE_BUTTON || errorCode == BiometricConstants.ERROR_USER_CANCELED || errorCode == BiometricPrompt.ERROR_CANCELED) return
authenticationlistener?.isBiometricAvailable = false
authenticationlistener?.onAuthenticationFailed()
}
})
promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle(getString(R.string.biometric_title))
.setSubtitle(getString(R.string.biometric_subtitle))
.setDescription(getString(R.string.biometric_description))
.setNegativeButtonText(getString(R.string.cancel))
.build()
biometricPrompt?.authenticate(promptInfo)
}