生物识别与震动 (Biometrics)
1. 触感反馈 (Haptics)
在 Compose 中,你可以通过 LocalHapticFeedback 轻松触发系统触感。
kotlin
@Composable
fun HapticSample() {
val haptics = LocalHapticFeedback.current
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Button(onClick = {
// 长按触感
haptics.performHapticFeedback(HapticFeedbackType.LongPress)
}) {
Text("长按震动")
}
Button(onClick = {
// 文本处理触感 (轻微)
haptics.performHapticFeedback(HapticFeedbackType.TextHandleMove)
}) {
Text("轻微震动")
}
}
}2. 生物识别 (Biometrics)
使用 AndroidX Biometric 库实现指纹/面容登录。
依赖
kotlin
implementation("androidx.biometric:biometric:1.1.0")封装 BiometricPrompt
kotlin
@Composable
fun BiometricAuthScreen(onAuthSuccess: () -> Unit) {
val context = LocalContext.current
val activity = context as? FragmentActivity ?: return
// 检查硬件是否可用
val biometricManager = BiometricManager.from(context)
val canAuthenticate = biometricManager.canAuthenticate(
BiometricManager.Authenticators.BIOMETRIC_STRONG
) == BiometricManager.BIOMETRIC_SUCCESS
val executor = ContextCompat.getMainExecutor(context)
val promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle("请验证身份")
.setSubtitle("使用指纹或面容登录")
.setNegativeButtonText("取消")
.build()
val biometricPrompt = remember {
BiometricPrompt(
activity,
executor,
object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
onAuthSuccess()
}
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
// 处理错误
}
}
)
}
Button(
onClick = { biometricPrompt.authenticate(promptInfo) },
enabled = canAuthenticate
) {
Text("生物识别登录")
}
}