Search code examples
android-biometric-prompt

How can i implement face authentication using biometric prompt in android x?


But can i implement face authentication using biometric prompt or any other android api's in my app. If no, are there any sdk which I can use to implement this feature in my app??


Solution

  • You can use the BiometricPrompt class to create a prompt dialog that just uses any biometric credential the user has initialized (e.g. fingerprint but also face). You can create a authentication dialog with the following steps:

    Step 1: Add dependencies to your build.gradle file in app/

    dependencies {
        implementation 'androidx.biometric:biometric:1.0.1'
    }
    

    Step 2: display the authentication prompt

    private Executor executor;
    private BiometricPrompt biometricPrompt;
    private BiometricPrompt.PromptInfo promptInfo;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        executor = ContextCompat.getMainExecutor(this);
        biometricPrompt = new BiometricPrompt(MainActivity.this,
                executor, new BiometricPrompt.AuthenticationCallback() {
                
            @Override
            public void onAuthenticationSucceeded(
                    @NonNull BiometricPrompt.AuthenticationResult result) {
                super.onAuthenticationSucceeded(result);
                // authenticated
            }
    
            @Override
            public void onAuthenticationFailed() {
                super.onAuthenticationFailed();
                // authentication failed
            }
        });
    
        promptInfo = new BiometricPrompt.PromptInfo.Builder()
                .setTitle("Biometric Authentication")
                .setSubtitle("Log in with your biometric credentials")
                .build();
    }
    

    The dialog will be displayed by calling this method:

    biometricPrompt.authenticate(promptInfo);
    

    Check the android doc for further information.