【问题标题】:How to set proguard rule for Room library on Android如何在 Android 上为 Room 库设置 proguard 规则
【发布时间】:2018-12-10 06:52:56
【问题描述】:

在我的应用程序中,我想使用 Room 库来使用 database,最后为了 generate APK 我启用 minify 选项(proguard) 在Build.Gradle 中。

我使用以下版本的 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

如何解决这个问题?

【问题讨论】:

    标签: java android android-room android-proguard


    【解决方案1】:

    如果你使用 androidx

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

    【讨论】:

    • 实体呢,他们不需要任何-keep吗?
    • 通过添加解决实体:-keep @androidx.room.Entity class *,参见here
    【解决方案2】:

    在您的 proguard 文件中为 keep 部分添加以下行。

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

    【讨论】:

    • 感谢此修复,但再次向我显示此错误:Expecting java type before ';' in line 71 of file '/Volumes/M/Test Projects/MyApp/app/proguard-rules.pro' 对于此行:-keepclasseswithmembers class * {native ;}。我该如何解决?请帮帮我
    • 使用native <methods>;需要加标签<methods>
    【解决方案3】:

    你需要在proguard文件中加入这一行

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

    你的模型实体应该看起来像这样 add 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
    

    )

    【讨论】:

      猜你喜欢
      • 2015-08-26
      • 2019-04-02
      • 1970-01-01
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多