使用androidx BiometricPrompt实现指纹验证功能

这篇文章主要介绍了使用androidx BiometricPrompt实现指纹验证功能,对android指纹验证相关知识感兴趣的朋友跟随小编一起看看吧

androidsdk版本大于29之后,使用FingerprintManagerCompat进行指纹验证显示被废弃,FingerprintManagerCompat的使用方法这里不再叙述。骨骼要求使用新的api去完成指纹验证,当然,BiometricPrompt不仅能做指纹验证,本文只讲解怎么用BiometricPrompt做指纹验证。
官方api:https://developer.android.google.cn/reference/androidx/biometric/package-summary?hl=zh-cn

首先导包

 implementation 'androidx.biometric:biometric:1.0.1'

然后它的构造方法

 1.BiometricPrompt(@NonNull FragmentActivity fragmentActivity, @NonNull Executor executor, @NonNull AuthenticationCallback callback) 2. BiometricPrompt(@NonNull Fragment fragment, @NonNull Executor executor, @NonNull AuthenticationCallback callback)

两个构造方法参数基本一致,executor里面是一个runnable接口,在每次进行指纹操作后都会回调这个方法,注意:要想AuthenticationCallback的方法生效,必须在runnable里面执行runnable的run方法。
callback里面有三个回调方法,
1. onAuthenticationError(int errMsgId, CharSequence errString),指纹验证错误会调用此方法,errMsgId的值对应BiometricPrompt里面的常量
2. onAuthenticationSucceeded(@NonNull @NotNull BiometricPrompt.AuthenticationResult result),指纹验证成功后调用,通过result.getAuthenticationType获取验证成功的方式,参数类型自行查看。
3. onAuthenticationFailed() 识别失败调用,具体调用时机不太清楚。。可以参考官方文档说法

显示指纹验证需要一个BiometricPrompt.PromptInfo参数,会弹起一个弹窗进行显示,使用builder的方式初始化,可以设置title,subTitle,description,NegativeButtonText,用法如下

 new BiometricPrompt.PromptInfo.Builder().setTitle("title") .setSubtitle("subTitle") .setDescription("description") .setDeviceCredentialAllowed(false) .setNegativeButtonText("button").build()

需要注意的是setDeviceCredentialAllowed与setNegativeButtonText只能存在一个,即setNegativeButtonText不为空setDeviceCredentialAllowed必须为false
验证设备是否开启指纹通过BiometricManager.from(context).canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS方法;
代码展示:

 private BiometricPrompt biometricPrompt; private void startFinger(){ biometricPrompt = new BiometricPrompt(this, new Executor() { @Override public void execute(Runnable command) { command.run(); } }, new FingerCallBack()); biometricPrompt.authenticate( new BiometricPrompt.PromptInfo.Builder().setTitle("title") .setSubtitle("subTitle") .setDescription("description") .setDeviceCredentialAllowed(false) .setNegativeButtonText("button").build()); } private void cancelFinger() { if (biometricPrompt != null) { biometricPrompt.cancelAuthentication(); } } private class FingerCallBack extends BiometricPrompt.AuthenticationCallback { @Override public void onAuthenticationError(int errMsgId, CharSequence errString) { super.onAuthenticationError(errMsgId, errString); Log.e("fingers", "onAuthenticationError"); } @Override public void onAuthenticationSucceeded(@NonNull @NotNull BiometricPrompt.AuthenticationResult result) { super.onAuthenticationSucceeded(result); cancelFinger(); Log.e("fingers", "识别成功 onAuthenticationSucceeded"); } @Override public void onAuthenticationFailed() { super.onAuthenticationFailed(); Log.e("fingers", "onAuthenticationFailed  "); } }

以上就是使用androidx BiometricPrompt实现指纹验证功能的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 移动