如何替换已弃用的 KeyGenParameterSpec.Builder.setUserAuthenticationValidityDurationSeconds?

问题描述

从 android 11 开始,setUserAuthenticationValidityDurationSeconds 被弃用,取而代之的是 KeyGenParameterSpec.Builder 中的 setUserAuthenticationParameters,但接缝对以前的版本有任何支持。

那么,最好的解决方案是什么?

KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(...)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R)
    builder.setUserAuthenticationParameters(timeout,KeyProperties.AUTH_DEVICE_CREDENTIAL | KeyProperties.AUTH_BIOMETRIC_STRONG);
else
    //noinspection deprecation
    builder.setUserAuthenticationValidityDurationSeconds(timeout);

这个?

解决方法

您不需要迁移实际的密钥,当您准备好支持 Android 11 时,您可以切换到类似的东西,(不要忘记为新 API 设置 b)>

compileSdkVersion 30

您可以这样做,因为在内部 val timeout = 30 //seconds val builder = KeyGenParameterSpec.Builder(...) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { builder.setUserAuthenticationParameters(timeout,KeyProperties.AUTH_DEVICE_CREDENTIAL or KeyProperties.AUTH_BIOMETRIC_STRONG ) } else { builder.setUserAuthenticationValidityDurationSeconds(timeout) } 正在做同样的事情。唯一的例外是如果您使用 setUserAuthenticationValidityDurationSeconds 作为超时调用 setUserAuthenticationValidityDurationSeconds。在这种情况下,新 API 的等效项是 -1

您可以查看 here 两种情况的源代码。

PS:上面的代码是 minAPI 24,如果你在较低的 API 级别,你需要在更多的构建检查中包装上面的代码。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...