如果您在活动中创建 biometricPrompt 和 promptInfo,它工作正常。但我无法让它在片段中工作。
这是一个片段内部,它在 OnViewCreated 内部被调用。您在活动中执行相同的操作效果很好,一种解决方案是从活动中传递 biometricPrompt 和 PromptInfo 并将其传递到片段中。
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)
}