Android

[Android/Java] 지문(생체) 인식 구현

윤정e다 2022. 2. 23. 18:03

구현 방법

Android 9.0 이후로 fingerprint가 deprecated 되고 BiometricPrompt를 참조한다.

 

Menifest 권한 추가
<!-- 지문 인식 권한 -->
<uses-permission android:name="android.permission.USE_BIOMETRIC" />

 

 

build.gradle
dependencies {
    //지문 인식 권한
    implementation 'androidx.biometric:biometric:1.1.0'
 }

 

 

activity_main.xml

나는 데이터바인딩을 사용하기 위해 <layout> 태그로 감쌌다. 데이터 바인딩 자료는 여기에 있으니 참고!!

 

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".FragmentHome">

        <Button
            android:id="@+id/button_auth_fingerprint"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:text="지문 인증하기"
            android:textSize="15dp"
            android:padding="16dp"/>
     </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

 

 

MainActivity.java
public class MainActivity extends AppCompatActivity {
	private static final String TAG="MainActivity";

	private Executor executor;
	private BiometricPrompt bioetricPrompt;
	private BiometricPrompt.PromptInfo promptInfo;
	private BiometricManager biometricManager;

	ActivityMainBinding binding;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		binding=DataBindingUtil.setContentView(this, R.layout.activity_main);

		//생체 인식 인증을 사용할 수 있는지 확인
		biometricManager = BiometricManager.from(context);
		switch (biometricManager.canAuthenticate(BIOMETRIC_STRONG | BiometricManager.Authenticators.DEVICE_CREDENTIAL)) {
			case BiometricManager.BIOMETRIC_SUCCESS:
				//생체 인증 가능
				Log.d(TAG, "App can authenticate using biometrics.");
				break;
			case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
				//기기에서 생체 인증을 지원하지 않는 경우
				Log.e(TAG, "No biometric features abailable on this device.");
				break;
			case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
				//생체 인식 정보가 등록되지 않은 경우
				Log.d(TAG, "Biometric features are currently unavailable.");
				break;
			/*
			case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
				final Intent enrollIntent=new Intent(Settings.ACTION_BIOMETRIC_ENROLL);
				enrollIntent.putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED, BIOMETRIC_STRONG|DEVICE_CREDENTIAL);
				startActivityForResult(enrollIntent, REQUEST_CODE);
				break;
			*/
			default:
				//기타 실패
				Log.d(TAG, "Fail Biometric facility");
				break;
		}

		//생체 인증 시작
		executor = ContextCompat.getMainExecutor(context);
		biometricPrompt = new BiometricPrompt(this, executor, new BiometricPrompt.AuthenticationCallback() {

			@Override
			public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) {
				super.onAuthenticationError(errorCode, errString);
				Toast.makeText(getActivity().getApplicationContext(), R.string.auth_error_message, Toast.LENGTH_SHORT).show();
				Log.e("auth", "지문인식 에러 코드: " + errorCode);
				Log.d("auth", "지문인식 에러: " + errString);
			}


			@Override
			public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) {
				super.onAuthenticationSucceeded(result);
				Toast.makeText(getActivity().getApplicationContext(), R.string.auth_success_message, Toast.LENGTH_SHORT).show();
			}


			@Override
			public void onAuthenticationFailed() {
				super.onAuthenticationFailed();
				Toast.makeText(getActivity().getApplicationContext(), R.string.auth_fail_message, Toast.LENGTH_SHORT).show();
			}
		});

		promptInfo = new BiometricPrompt.PromptInfo.Builder()
			.setTitle("지문 인증")
			.setSubtitle("기기에 등록된 지문을 이용하여 지문을 인증해주세요.")
			.setNegativeButtonText("취소")
			.build();

		binding.buttonAuthFingerprint.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view){
				biometricPrompt.authenticate(promptInfo);
			}
		});
     }
}