如何在Android上为Room库设置Proguard规则

10
在我的应用程序中,我想使用Room库来使用数据库,最终启用Build.Gradle中的混淆选项(proguard)以生成APK

我使用的是以下版本的Room库:

implementation "android.arch.persistence.room:runtime:1.1.1"
annotationProcessor "android.arch.persistence.room:compiler:1.1.1"

我在proguard-rules中编写以下代码:

-dontwarn class android.arch.persistence.room.paging.LimitOffsetDataSource
-dontwarn interface android.arch.persistence.room.paging.LimitOffsetDataSource
-dontwarn class android.arch.util.paging.CountedDataSource
-dontwarn interface android.arch.util.paging.CountedDataSource

但当生成APK时,在Build选项卡中显示以下错误:

Unknown option 'android.arch.persistence.room.paging.LimitOffsetDataSource' in line 39 of file '/Volumes/M/Test Projects/MyApp/app/proguard-rules.pro'

请为这一行代码提示错误:

-dontwarn class android.arch.persistence.room.paging.LimitOffsetDataSource

如何解决这个问题?
3个回答

19

如果您使用androidx

-keep class * extends androidx.room.RoomDatabase
-keep @androidx.room.Entity class *
-dontwarn androidx.room.paging.**

5
实体们需要保持不变吗? - Krzysztof Kubicki
通过添加:-keep @androidx.room.Entity class *,解决了实体的问题,请参见此处 - User Rebo

2
在您的proguard文件的keep部分添加以下行。
-dontwarn android.arch.util.paging.CountedDataSource
-dontwarn android.arch.persistence.room.paging.LimitOffsetDataSource

谢谢,这个问题已经解决了,但是又出现了一个错误:在文件'/Volumes/M/Test Projects/MyApp/app/proguard-rules.pro'的第71行中,需要java类型之前的';',对于这一行:-keepclasseswithmembers class * {native ;}。我该如何修复它呢?请帮帮我。 - Dr. Jake
使用 native <methods>;,你需要添加标签 <methods> - karan

1

你需要在proguard文件中添加这行代码

-keepclassmembers,allowobfuscation class * {
@com.google.gson.annotations.SerializedName <fields>;
}

你的模型实体应该像这样添加 SerializedName("key")

@Entity
data class ListElement(

@NonNull
@PrimaryKey
@SerializedName("id")
@Expose
val id: Int,

@SerializedName("userId")
@Expose
val userId: Int,

@SerializedName("title")
@Expose
val title: String,

@SerializedName("completed")
@Expose
val completed: Boolean

)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接