如何在 android 中添加 r8 规则?

How to add r8 rules in android?

我们如何在 android 项目中添加 R8 规则以获取依赖项并从缩小和混淆中排除文件和包?

添加R8规则与progurad规则类似,但有些依赖我们不需要在R8中添加规则,文档中可能会提到。来自 Android Studio 3.4 R8 是默认代码收缩器。

build.gradle应用程序模块中添加这一行

 buildTypes {
    release {
        minifyEnabled true //Important step
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

Selectproguard-rules.pro

添加排除包或文件的规则

-keep class com.xyz.model.** { *; }

以上代码从 minifing 中排除了模型包,最好从 minifing 中排除你的网络 pojo class。

如果您添加的任何依赖项具有 proguard/R8 规则,请注意:像 Retrofit 这样的库我们不需要在 R8 中添加它,它将在相应的 github 页面中提到

    -keepattributes *Annotation*
-keepclassmembers class * {
    @org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }

# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
    <init>(java.lang.Throwable);
}

以上示例适用于绿色机器人 proguard 规则。只需将其复制粘贴到您的 proguard-rules.pro 文件

供参考:https://www.youtube.com/watch?v=yduedsaxfDw