这是因为Android10系统才开放面部识别
所以你的手机就算有面部解锁功能,调用这个Biometric库还是会调出指纹解锁。
还有一些手机即使是Android10也无法调用面部解锁,可能与厂商是否开放面部解锁功能有关。
依赖
dependencies {
implementation 'androidx.biometric:biometric:1.0.0-beta01'
}
主要代码
public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler();
private Executor executor = new Executor() {
@Override
public void execute(Runnable command) {
handler.post(command);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button biometricLoginButton = findViewById(R.id.biometric_login);
BiometricManager biometricManager = BiometricManager.from(this);
switch (biometricManager.canAuthenticate()) {
case BiometricManager.BIOMETRIC_SUCCESS:
Toast.makeText(this, "应用可以进行生物识别技术进行身份验证", Toast.LENGTH_SHORT).show();
biometricLoginButton.setOnClickListener(view -> showBiometricPrompt());
break;
case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
Toast.makeText(this, "该设备上没有搭载可用的生物特征功能", Toast.LENGTH_SHORT).show();
break;
case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
Toast.makeText(this, "生物识别功能当前不可用", Toast.LENGTH_SHORT).show();
break;
case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
Toast.makeText(this, "用户没有录入生物识别数据", Toast.LENGTH_SHORT).show();
break;
}
}
//生物认证的setting
private void showBiometricPrompt() {
BiometricPrompt.PromptInfo promptInfo =
new BiometricPrompt.PromptInfo.Builder()
.setTitle("Biometric login for my app") //设置大标题
.setSubtitle("Log in using your biometric credential") // 设置标题下的提示
.setNegativeButtonText("Cancel") //设置取消按钮
.build();
//需要提供的参数callback
BiometricPrompt biometricPrompt = new BiometricPrompt(MainActivity.this,
executor, new BiometricPrompt.AuthenticationCallback() {
//各种异常的回调
@Override
public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
Toast.makeText(getApplicationContext(),
"Authentication error: " + errString, Toast.LENGTH_SHORT)
.show();
}
//认证成功的回调
@Override
public void onAuthenticationSucceeded(
@NonNull BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
BiometricPrompt.CryptoObject authenticatedCryptoObject =
result.getCryptoObject();
// User has verified the signature, cipher, or message
// authentication code (MAC) associated with the crypto object,
// so you can use it in your app's crypto-driven workflows.
}
//认证失败的回调
@Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
Toast.makeText(getApplicationContext(), "Authentication failed",
Toast.LENGTH_SHORT)
.show();
}
});
// 显示认证对话框
biometricPrompt.authenticate(promptInfo);
}
}