Android/java: Transition / Migration from ProGuard

2020-01-27 06:40发布

问题:

I wonder how to make the transition / migration from ProGuard to R8.

Should I just remove the Proguard-related lines from my Gradle files and add the android.enableR8 = true line instead ?

Thanks.

回答1:

Proguard is developed and maintained by GuardSquare while R8 is developed and maintained by Android team which means they are two different products although R8 is compatible with Proguard.

As seen from here https://www.guardsquare.com/en/blog/proguard-and-r8

Compatibility of ProGuard and R8

The good news for developers is that R8 is backward compatible with ProGuard. If you have a working ProGuard configuration (maybe eclectically copied from Stackoverflow), you can carry that over to R8. It currently still ignores some options. Notably, R8 doesn't implement the options -whyareyoukeeping and -addconfigurationdebugging, which we consider essential to quickly get to a working configuration, as we've explained in a previous blog.

Yes, android.enableR8 = true will enable the R8 feature.

Also note that, R8 does not currently (as the time of Android Studio 3.2.1) support Android Archive Library (AAR) projects. It is used only when building APK files.


Edit #1

From @Archie, If you are using Gradle plugin version 3.4.0 and above, R8 is on by default.

See: https://developer.android.com/studio/releases#r8-default


Edit #2

For the transition from Proguard to R8, you can follow below steps:

1. Disable Proguard

Update the buildTypes { } configuration to disable Proguard, e.g. for release build type:

   android {
       ...
       buildTypes {
           release {
               useProguard false // <-- disable proguard
               minifyEnabled true // <-- enable minification
               proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
           }
       }
       ...
   }

On Android Studio 3.4, useProguard by default is false. And R8 is enabled by default.

2. (Optional) Set full R8 configurations report file

Add below line into your proguard-rules.pro to output a full report of all the rules that R8 applies when building your project.

// You can specify any path and filename.
-printconfiguration <your-path>/full-r8-config.txt

3. Generate the obfuscated app.

./gradlew assembleRelease

4. (Optional) Fine-tune and trouble shooting

Find your <your-path>/full-r8-config.txt to fine-tune the configuration or do trouble shooting if any.

References:

https://developer.android.com/studio/build/shrink-code.html#configuration-files