BiometricPrompt requires either Fragment or FragmentActivity in its constructor. I cannot find out how to use BiometricPrompt from a Composable screen, not in the documentation, not in any tutorial. Has anyone in here dealt with the same problem? Or is there any other way to use biometric authentication in a fully Compose built application?
5 Answers
Subclass your MainActivity
from FragmentActivity
, then in composable get your context:
val context = LocalContext.current as FragmentActivity
Check out some examples on github: https://github.com/search?l=kotlin&q=BiometricPrompt%20composable&type=Code

- 67,741
- 15
- 184
- 220
-
Check this blog post: https://fvilarino.medium.com/adding-a-pin-screen-with-biometric-authentication-in-jetpack-compose-a9bf7bd8acc9 – Francesc Aug 03 '21 at 15:01
-
Doesn't work, I'm getting an exception: java.lang.ClassCastException: com.example.testapp.MainActivity cannot be cast to androidx.fragment.app.FragmentActivity – Stefan Jun 26 '22 at 12:49
-
1@Hassa As the first sentence says, you need to subclass your `MainActivity` from `FragmentActivity` – Phil Dukhov Jun 26 '22 at 14:15
Ok, it was quite simple in the end, but has taken me hours, so here is the answer for anyone struggling with this.
Make sure, that your MainActivity inherits from FragmentActivity(). Then you will be able to cast LocalContext.current to FragmentActivity.
val context = LocalContext.current as FragmentActivity
val biometricPrompt = BiometricPrompt(
context,
authenticationCallback
)

- 65
- 1
- 7
replace ComponetActivity()
with FragmentActivity()
then use normal compose view from FragmentActivity()
setContent {
FingerPrintAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background
) {
Greeting("Android")
}
}
}
then everything works fine

- 589
- 4
- 10
For those that cannot change their activity base class, there is issuetracker.google.com/issues/178855209 to request for a biometric-compose
artifact. Unfortunately, as of version 1.2.0-alpha04
no work has been done towards it.

- 7,352
- 4
- 35
- 56
You can inherit from AppCompatActivity, which inherits from FragmentActivity, which inherits from ComponentActivity.
Then you can do:
inline fun <reified Activity : FragmentActivity> Context.getActivity(): Activity? {
return when (this) {
is Activity -> this
else -> {
var context = this
while (context is ContextWrapper) {
context = context.baseContext
if (context is Activity) return context
}
null
}
}
}
and then:
val activity = LocalContext.current.getActivity<MainActivity>()
val biometricPrompt = BiometricPrompt(
activity,
authenticationCallback
)

- 7,828
- 12
- 64
- 106