Last active
January 25, 2022 17:12
-
-
Save Jaosrikate/0029f144d4b51b829f5910eea4900c4d to your computer and use it in GitHub Desktop.
Biometric prompt Login Activity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LoginActivity : AppCompatActivity() { | |
private lateinit var biometricPrompt: BiometricPrompt | |
private lateinit var promptInfo: BiometricPrompt.PromptInfo | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_login) | |
biometricPrompt = createBiometricPrompt() | |
promptInfo = createPromptInfo() | |
findViewById<Button>(R.id.fingerprintBtn).setOnClickListener { authenticate() } | |
} | |
private fun createBiometricPrompt(): BiometricPrompt { | |
val executor = ContextCompat.getMainExecutor(this) | |
private val biometricCallback = object : BiometricPrompt.AuthenticationCallback() { | |
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { | |
super.onAuthenticationSucceeded(result) | |
Toast.makeText( | |
this, | |
"Authentication succeeded!", Toast.LENGTH_SHORT | |
).show() | |
//TODO: call service login bio | |
} | |
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { | |
super.onAuthenticationError(errorCode, errString) | |
//Authenticate error handle e.g. Biomatric Sensor Locked, Too many attempts case | |
} | |
override fun onAuthenticationFailed() { | |
super.onAuthenticationFailed() | |
//Authenticate failed. e.g. Wrong fingerprint | |
} | |
} | |
//The API requires the client/Activity context for displaying the prompt view | |
val biometricPrompt = BiometricPrompt(this, executor, callback) | |
return biometricPrompt | |
} | |
private fun buildBiometricPrompt(): BiometricPrompt.PromptInfo { | |
return BiometricPrompt.PromptInfo.Builder() | |
.setTitle(getString(R.string.bio_authen_title)) | |
.setDescription(getString(R.string.bio_authen_description)) | |
.setNegativeButtonText(getString(R.string.bio_authen_negative_button)) | |
.setConfirmationRequired(false) //Allows user to authenticate without performing an action, such as pressing a button, after their biometric credential is accepted. | |
.setAllowedAuthenticators(BIOMETRIC_WEAK) | |
.build() | |
} | |
private fun authenticate() { | |
if (checkCanAuthenticate()) { | |
biometricPrompt.authenticate(promptInfo) | |
} | |
} | |
private fun checkCanAuthenticate(): Boolean { | |
return BiometricManager.from(applicationContext).canAuthenticate(BIOMETRIC_WEAK) == BiometricManager.BIOMETRIC_SUCCESS | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment