升级androidx.annotation至1.6.0后@Keep等注解导入失败,求新解决方案
解决androidx.annotation:annotation:1.6.0导入@Keep/@NonNull/@StringRes失败的问题
核心原因
从androidx.annotation:annotation:1.6.0开始,Google对注解库做了拆分:@Keep注解被单独移到了androidx.annotation:annotation-keep这个独立依赖中,主annotation库仍保留@NonNull、@StringRes等通用注解,但如果依赖配置不全或存在版本冲突,就会出现导入失败的情况。
解决方案
补充依赖配置
在Module级别的build.gradle中,除了主annotation依赖,新增annotation-keep依赖:implementation "androidx.annotation:annotation:1.6.0" implementation "androidx.annotation:annotation-keep:1.6.0"清理缓存并重新构建
- 执行命令行清理:
./gradlew clean(Mac/Linux)或gradlew clean(Windows) - 在Android Studio中点击
File -> Sync Project with Gradle Files同步依赖 - 重新编译项目
- 执行命令行清理:
排查并解决版本冲突
如果上述操作后仍有问题,检查是否有第三方库引入了旧版本的annotation依赖导致冲突:- 运行
./gradlew dependencies查看依赖树,搜索androidx.annotation相关条目 - 若发现冲突,添加版本强制规则:
configurations.all { resolutionStrategy.force "androidx.annotation:annotation:1.6.0" resolutionStrategy.force "androidx.annotation:annotation-keep:1.6.0" }
- 运行
调整后,@Keep、@NonNull、@StringRes的导入即可正常工作,同时保留1.6.0版本注解库的特性。
内容的提问来源于stack exchange,提问作者KiraHoneybee
相关产品推荐
相关产品推荐

