Applying Proguard In An Android Application



What is Proguard?

ProGuard is a tool used to do the following in an Android application:

  • Minify the code.
  • Obfuscate the code.
  • Optimize the code.

So in this way, the Proguard makes the following impact:

  • Reduce the size of the application.
  • Remove the unused classes and methods that contribute to the 64K method counts limit of an Android application.
  • Makes the application difficult to reverse engineer by obfuscating the code.

To enable ProGuard, add minifyEnabled true to the build type in your build.gradle file.

As the code shrinking slows down the build time, so you should avoid using it on your debug build if possible. However, it’s important that you do enable code shrinking on your final APK used for testing because it might introduce bugs which you may not know.

The following snippet from a build.gradle file enables code shrinking for the release build:


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


With great power, comes great responsibility.

So, now let’s look at the important points that should be considered while applying the Proguard in your application.

  • Do not forget to add the Proguard rules in proguard-rules.pro file for any library that you have included in your project.

Let say you are using Okio library, you will have to add the following rule


-dontwarn okio.**


  • Add the rule for the classes on which you do not want to apply Proguard using keep class.

Let say you do not want to obfuscate the class AmitShekhar.java, then you have to add the following rule:


-keep class com.mindorks.AmitShekhar**


  • Do not use something like AwesomeFragment.class.getSimpleName() as a fragment TAG. Proguard may assign the same name (A.class) to two different fragments in different packages while obfuscating. In this case, two fragments will have the same TAG. It will lead to the bug in your application.
  • Keep your mapping file of the Proguard to trace back to the original code. You may have to upload it at different places like PlayStore Console for seeing the original stack-trace of the crashes.

Thanks for reading this article. Be sure to share this article if you found it helpful. It means a lot to me.

For more about programming, follow me and Mindorks , so you’ll get notified when we write new posts.

Join The Mindorks Community And Learn From Each Other.

Also, Let’s become friends on Twitter, Linkedin, Github and Facebook.