Gradle 的 Android 插件中的 "minifyEnabled" 和 "useProguard" 有什么区别?

What's the difference between "minifyEnabled" and "useProguard" in the Android Plugin for Gradle?

我看到 Android 插件 Gradle 有一个 minifyEnabled 属性 以及一个 useProguard 属性,如下:

android {
    buildTypes {
        debug {
            minifyEnabled true
            useProguard false
        }
        release {
            minifyEnabled true
            useProguard true
        }
    }
}

这两个属性有什么区别?或者,更确切地说,每个的含义是什么?

引用自tools.android.com

Built-in shrinker

Version 2.0 of Android Plugin for Gradle ships with an experimental built-in code shrinker, which can be used instead of ProGuard. The built-in shrinker supports fast incremental runs and is meant to speed up iteration cycles. It can be enabled using the following code snippet:

android {
    buildTypes {
        debug {
            minifyEnabled true
            useProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt')
        }
    }
}

The built-in shrinker can only remove dead code, it does not obfuscate or optimize. It can be configured using the same files as ProGuard, but will ignore all flags related to obfuscation or optimization.

Unlike ProGuard, we support using the built-in shrinker together with Instant Run: depending on the project, it may significantly decrease the initial build and install time. Any methods that become reachable after a code change will appear as newly added to the program and prevent an Instant Run hotswap.

只需启用 minifyEnabled 即可优化和混淆代码。 这是因为 useProguard true 是默认值,因此无需明确设置。

另请参阅: Obfuscation in Android Studio

您不再需要 useProguard true

当您将 minifyEnabled 属性 设置为 true 时,默认情况下启用 R8 代码收缩。

当您使用 Android Gradle 插件 3.4.0 或更高版本 构建项目时,该插件不再使用 ProGuard 来执行 compile-time 代码优化。相反,该插件与 R8 编译器一起根据 official document.

处理任务

如果您想使用 ProGuard 而不是 R8。在 gradle.properties 文件中添加这一行

 android.enableR8=false

我为我的发布 buildType 设置了 minifyEnabled true,它删除了整个枚举,我认为它是未使用的代码。这使我的应用程序因 NoSuchFieldException 而崩溃。我花了 4 个小时才找到这次崩溃的原因。 0/10 不能推荐 minifyEnabled。