前言
在当今数字时代,随着科技的不断发展,用户敏感信息尤为重要。从指纹到面部识别,再到虹膜扫描,生物识别技术为我们带来了便捷性和安全性。本次将构建一个简易的账户信息应用,运用生物识别技术来提高信息的安全性。
什么是 Biometric ?
Biometric 是一组 API 和框架,旨在为 Android 应用程序提供生物识别功能,以提高用户安全性和便利性。这些生物识别技术通常包括指纹识别、面部识别和虹膜扫描等。
三种不同的生物识别身份验证类型:
- BIOMETRIC_STRONG:强类型识别验证它要求用户提供强大的生物识别信息,例如指纹和虹膜扫描,这使得难以伪造和绕过验证。它提供了高级别安全性,适合处理敏感数据和交易类型的应用。
- BIOMETRIC_WEAK:弱类型识别验证使用人脸识别等不太安全的验证方法,与强类型相比可能更容易欺骗或绕过验证,此方式适合安全性较低的应用。
- DEVICE_CREDENTIAL:此验证方式不涉及生物识别,而是依赖于手机设备的安全性,例如 PIN、密码或图案。当手机不具备生物识别技术时,可使用此方式。
示例
在开始之前先来看看成品效果如何,当我们启动应用之后会立马弹出验证弹窗进行识别身份,在未完成识别之前,应用内部的信息都是无法查看的。
添加依赖库
在模块级别的 build.gradle 文件中添加以下依赖:
buildscript {
dependencies {
classpath "com.google.dagger:hilt-android-gradle-plugin:2.38.1"}}
plugins {...}
在项目级别的 build.gradle 文件中添加以下依赖:
plugins {...
id 'dagger.hilt.android.plugin'
id 'kotlin-kapt'
}
android {...}
dependencies {...// Room
implementation "androidx.room:room-runtime:2.4.3"
kapt "androidx.room:room-compiler:2.4.3"
implementation "androidx.room:room-ktx:2.4.3"
annotationProcessor "androidx.room:room-compiler:2.4.3"// Dagger + Hilt
implementation "com.google.dagger:hilt-android:2.38.1"
kapt "com.google.dagger:hilt-compiler:2.38.1"
implementation "androidx.hilt:hilt-navigation-compose:1.0.0"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03"
kapt "androidx.hilt:hilt-compiler:1.0.0"//生物识别
implementation "androidx.biometric:biometric:1.1.0"}
编写数据库部分
创建存储账户信息实体类 AccountEntity 、数据访问对象 AccountDao 以及 Room 数据库文件 AccountDatabase 。
@Entity(tableName ="account")dataclassAccountEntity(@PrimaryKey(autoGenerate =true)val id: Int?=null,val type: String,val account: String,val password: String
)//------------------------------@Daointerface AccountDao {@InsertsuspendfunaddAccount(account: AccountEntity)@Query("SELECT * FROM account")fungetAccounts():Flow<List<AccountEntity>>@DeletesuspendfundeleteAccount(account: AccountEntity)}//------------------------------@Database(
entities =[AccountEntity::class],
version =1)abstractclass AccountDatabase :RoomDatabase(){abstractfungetDao(): AccountDao
companionobject{constval DATABASE_NAME ="accounts_db"}}
依赖注入
创建 DatabaseModule 单例对象,使用 Hilt 提供的注解标记,它负责管理全局应用中的单例对象,里面有一个提供数据库实例的方法,在需要的地方直接在构造器声明即可,它会自动注入该对象。
@Module@InstallIn(SingletonComponent::class)object DatabaseModule {@Provides@SingletonfunprovideAccountDatabase(@ApplicationContext context: Context): AccountDatabase {return Room.databaseBuilder(
context,
AccountDatabase::class.java,
AccountDatabase.DATABASE_NAME
).build()}}
编写业务逻辑
在 MainViewModel 中使用特有注解 HiltViewModel 并注入数据库实例对象。注意:一般操作数据库是在 Repository 中进行的,这里为了演示就简化了,直接在 ViewModel 中操作。
@HiltViewModelclass MainViewModel @Injectconstructor(privateval db:AccountDatabase
):ViewModel(){//账户列表privateval _accounts = mutableStateOf<List<AccountEntity>>(emptyList())val accounts: State<List<AccountEntity>>= _accounts
init{getAllAccounts()}//添加账户funaddAccount(
type: String,
account: String,
password: String
){
viewModelScope.launch{
db.getDao().addAccount(AccountEntity(
type=type,
account=account,
password=password
))}}//删除账户fundeleteAccount(account: AccountEntity){
viewModelScope.launch{
db.getDao().deleteAccount(account)}}//获取所有账户privatefungetAllAccounts(){
viewModelScope.launch{
db.getDao().getAccounts().collect{ result ->
_accounts.value = result
}}}}
使用 Biometric API(核心)
创建 BiometricPrompt 实例,它是 AndroidX 中提供的组件,可帮助我们轻松快速的将生物识别添加到应用中。
BiometricPrompt.PromptInfo.Builder()
:用于创建提示信息,提示框的标题和描述以及配置身份验证的方式。BiometricPrompt
实例通过 activity, executor, callback 三部分构造,其中 executor 负责主线程上的回调处理,callback 的类型为 BiometricPrompt.AuthenticationCallback ,回调三个身份验证处理的回调方法。biometricPrompt.authenticate(promptInfo)
调用身份验证方法,传入提示信息向用户显示身份验证对话框。
object BiometricHelper {/** 创建提示信息 **/privatefuncreatePromptInfo(): BiometricPrompt.PromptInfo =
BiometricPrompt.PromptInfo.Builder().setTitle("SecretAccountApp").setDescription("使用你的指纹或者面部来验证你的身份").setAllowedAuthenticators(BIOMETRIC_STRONG or BIOMETRIC_WEAK or DEVICE_CREDENTIAL).build()//setConfirmationRequired(true)//setNegativeButtonText("取消")/** 创建生物识别提示 **/funshowBiometricPrompt(
activity: AppCompatActivity,
onSuccess:(BiometricPrompt.AuthenticationResult)-> Unit
){val executor = ContextCompat.getMainExecutor(activity)val callback =object: BiometricPrompt.AuthenticationCallback(){overridefunonAuthenticationError(
errorCode: Int,
errString: CharSequence
){super.onAuthenticationError(errorCode, errString)// 处理身份验证错误
Log.e("HGM","onAuthenticationError: $errString")}overridefunonAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult){super.onAuthenticationSucceeded(result)// 处理身份验证成功onSuccess(result)}overridefunonAuthenticationFailed(){super.onAuthenticationFailed()// 处理身份验证失败
Log.e("HGM","onAuthenticationFailed: 验证失败")}}returnBiometricPrompt(activity, executor, callback).authenticate(createPromptInfo())}}
注意:创建 PromptInfo 实例时不能同时调用 setNegativeButtonText()和 setAllowedAuthenticators() 一旦你设置了否定取消文本按钮,意味着结束身份验证,而后者可以设置使用多个身份验证方法。
编写UI
由于本文得侧重点不在于 UI,所以直接贴上代码。
这里添加一个生命周期的监听者,在应用启动的时候自动执行身份验证,当应用返回到桌面或者重新启动会重置状态,每次进入都需要进行验证。
@ComposablefunOnLifecycleEvent(
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
onEvent:(LifecycleOwner, Lifecycle.Event)-> Unit
){DisposableEffect(lifecycleOwner){val observer = LifecycleEventObserver { source, event ->onEvent(source, event)}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)}}}
页面由一个简单的列表和按钮组成,代码过长重点部分:
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)@ComposablefunAccountScreen(
viewModel: MainViewModel =hiltViewModel()){val activity = LocalContext.current as AppCompatActivity
// 是否显示账号输入框var showDialog by remember {mutableStateOf(false)}// 身份验证的状态val authorized = remember {mutableStateOf(false)}// 执行身份验证val authorize:()-> Unit ={
BiometricHelper.showBiometricPrompt(activity){
authorized.value =true}}// 模糊值val blurValue byanimateDpAsState(
targetValue =if(authorized.value)0.dp else15.dp,
animationSpec =tween(500))// 监听应用的声明周期
OnLifecycleEvent { _, event ->when(event){
Lifecycle.Event.ON_RESUME ->authorize()
Lifecycle.Event.ON_PAUSE -> authorized.value =falseelse-> Unit
}}Scaffold(
floatingActionButton ={
Column {FloatingActionButton(onClick ={
showDialog =true}){Icon(
imageVector = Icons.Default.Add,
contentDescription =null)}Spacer(modifier = Modifier.height(12.dp))FloatingActionButton(onClick ={authorize()}){Icon(
imageVector = Icons.Default.Lock,
contentDescription =null)}}}){ innerPadding ->Box(
modifier = Modifier
.fillMaxSize().padding(innerPadding)){LazyColumn(
modifier = Modifier
.fillMaxSize().padding(12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)){items(viewModel.accounts.value){Box(
modifier = Modifier
.animateItemPlacement(tween(500)).fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(MaterialTheme.colorScheme.primary).padding(16.dp).blur(
radius = blurValue,
edgeTreatment = BlurredEdgeTreatment.Unbounded
)){...}}}}if(showDialog){Dialog(
onDismissRequest ={ showDialog =false}){...}}}}
修改 MainActivity 的继承父类为 AppCompatActivity 并且修改主题样式,因为创建 BiometricPrompt 时需要类型为 FragmentActivity 参数,AppCompatActivity 是 FragmentActivity 的子类并扩展了它。
@AndroidEntryPointclass MainActivity :AppCompatActivity(){overridefunonCreate(savedInstanceState: Bundle?){super.onCreate(savedInstanceState)
setContent {
SecretAccountAppTheme {Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
){AccountScreen()}}}}}
自定义 MyApp 继承 Application 程序类,使用 @HiltAndroidApp 注解作为标识应用程序的主类,这里没有初始化工作就不需要写东西,在注册清单中应用它。
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"><!-- 开启权限 --><uses-permission android:name="android.permission.USE_BIOMETRIC"/><application
android:name=".MyApp"...>....</application></manifest>
准备测试指纹
如果你使用模拟器,需要打开设置->安全中先添加 PIN 码后,添加一个指纹用于测试。
添加测试指纹
运行效果
使用刚才添加的指纹一进行验证,通过后会显示应用内的信息,如视频中使用指纹二会显示验证失败。并且每次进入应用都需要进行身份验证,保证了数据不会泄露。如果你想使用面容验证,那就需要删除掉你的指纹,添加一个面容数据,它会自动识别你已添加的生物识别数据。
最后这只是一个简易的实例项目,更多内容请结合实际项目,欢迎 Github 提交 Issue。
生物识别运行效果
源码地址:
https://github.com/AAnthonyyyy/SecretAccountApp
官方文档:
https://developer.android.com/training/sign-in/biometric-auth?hl=zh-cn
关注我,与你分享更多技术文章。麻烦右下角区域点个【赞】支持一下吧!更多内容请关注下方微信公众号。
版权归原作者 AAnthonyyy 所有, 如有侵权,请联系我们删除。