生物辨識技術在現代移動應用程式中變得越來越重要,不僅提供了更安全的身份驗證方式,還提高了使用者體驗。Android 提供了一個強大的 API,稱為 BiometricPrompt,用於實現生物辨識功能。今天的文章,我們將深入探討 BiometricPrompt,並使用一個簡單的範例來介紹如何在 Android 應用程式中使用它。
上下兩個按鈕分別是指紋和PIN碼的辨識。
dependencies {
implementation 'androidx.biometric:biometric:1.2.0'
}
private void checkBiometricSupport() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
switch (biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG)){
//此裝置可以使用生物辨識
case androidx.biometric.BiometricManager.BIOMETRIC_SUCCESS:
Log.e("TAG", "App can authenticate using biometrics.");
break;
//此裝置無法使用生物辨識
case androidx.biometric.BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
Log.e("TAG", "No biometric features available on this device.");
break;
//生物識別功能目前不可用
case androidx.biometric.BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
Log.e("TAG", "Biometric features are currently unavailable.");
break;
//用戶尚未建立生物辨識帳號資料
case androidx.biometric.BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
Log.e("TAG", "The user hasn't associated any biometric credentials with their account.");
break;
//使否可以使用生物辨識(已棄用)
default:
throw new IllegalStateException("Unexpected value: "+biometricManager.canAuthenticate());
}
}
}
private void createBiometricPrompt() {
//設置驗證CallBack
biometricPrompt = new androidx.biometric.BiometricPrompt(this, ContextCompat.getMainExecutor(this), new androidx.biometric.BiometricPrompt.AuthenticationCallback() {
@Override
public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
Log.e("GOGO", errString.toString());
}
@Override
public void onAuthenticationSucceeded(@NonNull androidx.biometric.BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
Log.e("GOGO", "成功");
}
@Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
Log.e("GOGO", "失敗");
}
});
}
//叫出指紋辨識
public void OnFingerClick(View view){
buildFingerPrint();
biometricPrompt.authenticate(promptInfo.build());
}
//叫出Pin碼辨識
public void OnPinClick(View view){
buildPinPrint();
biometricPrompt.authenticate(promptInfo.build());
}
//建立指紋辨識的視窗
private void buildFingerPrint() {
promptInfo = new androidx.biometric.BiometricPrompt.PromptInfo.Builder()
.setAllowedAuthenticators(androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG)
.setTitle("驗證")
.setSubtitle("請輸入指紋")
.setNegativeButtonText("取消");
}
//建立Pin辨識的視窗
private void buildPinPrint() {
promptInfo = new BiometricPrompt.PromptInfo.Builder()
//設定驗證(DEVICE_CREDENTIAL 為最基本PIN、圖形等、BIOMETRIC_WEAK、BIOMETRIC_STRONG(最高等級)(BIOMETRIC表生物辨識逼本也有指紋))
.setAllowedAuthenticators(BiometricManager.Authenticators.DEVICE_CREDENTIAL)
.setTitle("PIN")
.setSubtitle("請輸入PIN");
}
因為 Android 手機會把驗證截圖的畫面屏蔽,所以就不能給你們看成果了,就靠你們自己實作啦!!!!