在 Android 的 Gradle 插件中,“ minifyEnable”和“ useProGuard”有什么区别?

我注意到 Android 的 Gradle 插件有一个 minifyEnabled属性和一个 useProguard属性,如下所示:

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

这两个属性之间有什么区别? 或者说,它们各自的含义是什么?

71675 次浏览

Quoting from 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.

Just enable minifyEnabled will have code both optimized and obfuscated. This is because useProguard true is default so no need to set it explicitly.

See also: Obfuscation in Android Studio

You don't need useProguard true anymore.

Code shrinking with R8 is enabled by default when you set the minifyEnabled property to true.

When you build your project using Android Gradle plugin 3.4.0 or higher, the plugin no longer uses ProGuard to perform compile-time code optimization. Instead, the plugin works with the R8 compiler to handle the tasks according to the official document.

If you want to use ProGuard instead of R8. Add this line in the gradle.properties file

 android.enableR8=false

I set minifyEnabled true for my release buildType and it removed an entire enum which it thougt to be unused code i guess. This made my app crash due to a NoSuchFieldException. Took me 4 hours to find the reason for this crash. 0/10 can not recommend minifyEnabled.