2022-04-27|閱讀時間 ‧ 約 5 分鐘

Android-BiometricManager 指紋登入

主要物件:

BiometricManager
-檢查使用者是否有指紋辨識or是否設置密碼

BiometricPrompt
-初始化指紋視窗 並且 呼叫指紋視窗

BiometricPromptInfo
-指紋視窗的一些設定 Title , Description ...

Coding:

這邊會先建議建立 BiometricManager

主要是因為,他能判斷使用者是否有支持指紋或者設置Pin碼
  • BIOMETRIC_ERROR_NO_HARDWARE:沒有指紋
  • BIOMETRIC_ERROR_HW_UNAVAILABLE:沒有獲取到硬體
  • BIOMETRIC_ERROR_NONE_ENROLLED:沒有設定生物辨識
val biometricManager = BiometricManager.from(this) 
when (biometricManager.canAuthenticate()) {     
BiometricManager.BIOMETRIC_SUCCESS ->         
  Log.d("TAG", "App can authenticate using biometrics.")     
BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE ->        
   Log.e("TAG", "No biometric features available on this device.") 
BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE ->         
   Log.e("TAG", "Biometric features are currently unavailable.") 
BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED ->        
   Log.e("TAG", "The user hasn't associated any biometric credentials with their account.") 
}

建立 executors and callback(BiometricPrompt.AuthenticationCallback)
val executors = ContextCompat.getMainExecutor(this)
val callback = object : BiometricPrompt.AuthenticationCallback(){
   override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
       super.onAuthenticationError(errorCode, errString)
   }

   override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
       super.onAuthenticationSucceeded(result)
       finish()
       startActivity(Intent(this@LoginActivity,MainActivity::class.java))
   }

   override fun onAuthenticationFailed() {
       super.onAuthenticationFailed()
   }
}
再來 建立 BiometricPromptInfo
val biometricPromptInfo = BiometricPrompt.PromptInfo.Builder()
       .setTitle("Authentication")
       .setDescription("")
       .setDeviceCredentialAllowed(true)
       .build()
最後 BiometricPrompt
biometricPrompt.authenticate -呼叫指紋
biometricPrompt = BiometricPrompt(this, executors, callback) 
biometricPrompt.authenticate(biometricPromptInfo)
結果:
Result
Result

GitHub:

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.