アプリを生体認証させるためのAPIである「BiometricPrompt」についてまとめます。
対応バージョン
Android 9 以降
Android 9 未満の場合は、AndroidXのサポートライブラリを使うことにより、Android 6 以降であれば使えるみたいです。(未確認)
対応機種
認証機能が搭載されていても、BiometricPromptに対応していないものがありましたので分かり次第まとめておきます。
Model | Biometric Authentication | 備考 |
---|---|---|
Pixel 3 / 3XL | 顔認証OK | |
Xperia XZ1 | 指紋認証OK | |
AQUOS sense2 | 顔認証NG | 顔認証はプリインされているが画像処理 |
Reference
ドコモ対応機種
https://www.nttdocomo.co.jp/service/bio/compatible_model/security_face_attestation.html
Sample Code
これで動きました。ただ、生体認証を予めOSで設定しておく必要があります。
package sec.co.jp.biometrics
import android.content.DialogInterface
import android.hardware.biometrics.BiometricPrompt
import android.os.Bundle
import android.os.CancellationSignal
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class SubActivity : AppCompatActivity() {
private lateinit var cancelSignal: CancellationSignal
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sub)
}
override fun onResume() {
super.onResume()
}
private fun auth_check() {
Log.d("test", "auth_check")
cancelSignal = CancellationSignal()
val builder = BiometricPrompt.Builder(this)
builder.setTitle("生体認証します")
builder.setNegativeButton("キャンセル", mainExecutor, DialogInterface.OnClickListener { dialogInterface, i ->
cancelSignal.cancel()
Toast.makeText(this@SubActivity, "キャンセル", Toast.LENGTH_SHORT).show()
})
builder.build().authenticate(cancelSignal, mainExecutor, object: BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
when (errorCode) {
BiometricPrompt.BIOMETRIC_ERROR_NO_BIOMETRICS ->
Toast.makeText(this@SubActivity, "非対応です。", Toast.LENGTH_SHORT).show()
else -> {
Toast.makeText(this@SubActivity, "その他のエラーです。", Toast.LENGTH_SHORT).show()
// 所定回数失敗すると生体認証ダイアログすら出なくなる
}
}
}
override fun onAuthenticationHelp(helpCode: Int, helpString: CharSequence) {
throw RuntimeException("Stub!")
}
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
Toast.makeText(this@SubActivity, "認証成功です。", Toast.LENGTH_SHORT).show()
}
override fun onAuthenticationFailed() {
Toast.makeText(this@SubActivity, "認証失敗です。", Toast.LENGTH_SHORT).show()
}
})
}
}
Reference
【Android】BiometricPromptと指紋認証機能の実装方法について
https://qiita.com/hotdrop_77/items/75fa88fbcb1594338047
[Android / Kotlin] BiometricPrompt(生体認証)をちょっとだけ
https://qiita.com/takusan_23/items/ef58699924cf3e07e377
Android 9 PieのBiometricPromptをさらっと試した
https://qiita.com/devnokiyo/items/1fa9ad291a6211ef1595