CommonsWare CommonsWare - 1 year ago 43
Android Question

How Do I Teach ProGuard to Get Rid of Something It Is Keeping That I Am Not Using?

I have an Android project with a

proguard-rules.pro
file for the
app
module that contains only the following:

# ProGuard rules
-dontobfuscate
-dontwarn android.arch.util.paging.CountedDataSource
-dontwarn android.arch.persistence.room.paging.LimitOffsetDataSource


I am not keeping anything myself. All
-keep
rules are coming from something else, whether that is the rules provided by
getDefaultProguardFile('proguard-android-optimize.txt')
or from rules packaged in libraries.

However, stuff is being kept that I am not using. If I use the Android Studio APK Analyzer on my
release
build, while lots of things are removed by ProGuard, lots of other things are kept that I am not referencing.

For example: through transitive dependencies, I have the Support Library module that contains
ViewPager
in the app's dependencies tree. However, I am not (presently) using
ViewPager
in this app. Despite this, something is causing it to be kept, as the APK Analyzer shows 107 defined methods for
android.support.v4.view.ViewPager
, including its constructor.

I could use various ProGuard options to track down why this is being kept. However, it is not coming from my rules. There is no
-keep
of my own that needs fixing — the
-keep
is coming from somebody else, presumably a Google engineer.

So, how do I get rid of
ViewPager
? Is there a way that I can override the
-keep
rule that is causing it to be kept (e.g., using
allowshrinking
)? If so, how does ProGuard, as invoked by Android Studio, determine whose
-keep
rule wins?

Answer Source

The ViewPager class isn't kept in a small app that I just checked, so it must be other code or other rules in your project indeed.

You can start with letting ProGuard print out the chain that triggers ViewPager to be kept:

-whyareyoukeeping class android.support.v4.view.ViewPager

You may need to repeat this a number of times for various classes and methods to get to the root cause. ProGuard doesn't print out which rule exactly is responsible -- admittedly, this would be a useful feature.

You can then look for the proguard.txt file in build/intermediates/exploded-aar that contains a matching rule.

As for a solution at that point:

  • It is not possible to override -keep rules; they only accumulate.
  • As far as I know, the Android Gradle plugin also doesn't support disabling overly conservative proguard.txt files in libraries, so you'd need to create a custom .aar file with the updated rule, or send a suggestion to the developers of the library.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download