正确覆盖 proguard 选项

Correctly override proguard options

我在当前项目中使用 ProGuard,并决定尝试优化 android 配置(使用 gradle):

proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

我没有找到任何关于 proguard 和 android 兼容的版本执行的优化的明确文档:

-optimizations !code/simplification/arithmetic,!code/simplification/cast,!field/*,!class/merging/* 

如果应用的最低 sdk 版本是 11,它们是最新的吗?

所以我决定覆盖它以在 proguard-rules.pro:

中试一试
-optimizations **
-printconfiguration "result.pro"

但最终配置与我预期的不一样。它包含所有组合的规则:

-optimizations !code/simplification/arithmetic,!code/simplification/cast,!field/*,!class/merging/*,**

那么如何在 ProGuard 中正确覆盖选项呢?或者这一行可能等于 -optimizations ** ?

我试错了几次,但最终还是找到了。例如,要覆盖默认的 ProGuard 优化以应用除 code/simplification/arithmetic 之外的所有内容,则:

  1. 在您的 ProGuard 文件中添加一行 -optimizations 并使用 * 来表示 all。例如,下面一行:

    -optimizations !code/simplification/arithmetic,*
    

    表示"enable all optimizations except code/simplification/arithmetic"。 the official website 中提供了可用优化列表,您可以使用 * 到 enable/disable 类 的优化(例如 !field/*)。

  2. 您必须通过交换 Gradle 中 proguard-rules.progetDefaultProguardFile('proguard-android.txt') 的顺序来确保您的 ProGuard 规则文件在默认 ProGuard 文件之前加载文件,以便 proguard-rules.pro 先出现:

    buildTypes {
      release {
        minifyEnabled false
        proguardFiles 'proguard-rules.pro', getDefaultProguardFile('proguard-android.txt')
      }
    }
    

输出现在应该如下所示:

Optimizing...
  Number of finalized classes:                 68
  Number of unboxed enum classes:              1
  Number of vertically merged classes:         0
  Number of horizontally merged classes:       3
  Number of removed write-only fields:         0   (disabled)
  Number of privatized fields:                 58
  Number of inlined constant fields:           375
  Number of privatized methods:                13
  Number of staticized methods:                37
  Number of finalized methods:                 210
  Number of removed method parameters:         290
  Number of inlined constant parameters:       236
  Number of inlined constant return values:    239
  Number of inlined short method calls:        35
  Number of inlined unique method calls:       114
  Number of inlined tail recursion calls:      0
  Number of merged code blocks:                4
  Number of variable peephole optimizations:   723
  Number of arithmetic peephole optimizations: 10
  Number of cast peephole optimizations:       0
  Number of field peephole optimizations:      0
  Number of branch peephole optimizations:     42
  Number of string peephole optimizations:     35
  Number of simplified instructions:           369
  Number of removed instructions:              5019
  Number of removed local variables:           154
  Number of removed exception blocks:          0
  Number of optimized local variable frames:   201