AndroidPub
Published in

AndroidPub

Android DTT #16 — Why You Want to Turn On ProGuard Minification

Keep It Small, Keep It Secret

By default, ProGuard minification is turned off so your APK will contain unused method/class/field. And they will be pretty easy to read with help from simple tools. I have a simple project with MainActivity, FamilyData and FamilyMember. But there’s no reference made to the last two.

I run the ./gradlew assembleRelease and use DEX decompiler tools jadx to decompile the APK. It’s like looking into code in Github:

As you can see. The FamilyData and FamilyMember, not only can be easily read but also exist in the APK despite not being used anywhere in the project, making the APK size bigger than it needs to be.

Enable ProGuard

ProGuard can handle these problems. To enable ProGuard minification, open build.gradle in your app module. Then add/change the minifyEnabled to true in buildTypes

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

You can specify various configurations of ProGuard in proguard-rules.pro. One example is to keep the name of classes along with the fields because those classes will be converted into JSON. You can read more at https://www.guardsquare.com/en/proguard/manual/usage

Tips: If you’re adding a library into your apps, make sure to check if that library requires ProGuard configuration added in order for it to works properly.

When I tried to decompile the APK again, here’s what I got:

Both FamilyData and FamilyMember were not included in the APK. And when I try to create reference to both of them in MainActivity:

private void initData() {
FamilyData familyData = new FamilyData();
familyData.setName("The Awesomes");
List<FamilyMember> familyMembers = new ArrayList<>();
FamilyMember mrAwesome = new FamilyMember().setName("Mr. Awesome").setAge(40);
FamilyMember coolKid = new FamilyMember().setName("Cool Kid").setAge(12).setParent(mrAwesome);

familyMembers.add(mrAwesome);
familyMembers.add(coolKid);

familyData.setFamilyMembers(familyMembers);
}

Here’s the result:

Now that’s is harder to read. ProGuard really shines when your code base is big enough since it’ll reduce your APK size significantly, save user bandwidth and make user happy.

You can read more about shrinking your APK size in the official android documentation: https://developer.android.com/studio/build/shrink-code.html

If you like this, hit that heart button and recommend it to your friends.

ADTT (Android Development Tips and Tricks) is a 31 series of blog posts that I’m trying to finish in throughout May. Click here for index.

--

--

The (retired) Pub(lication) for Android & Tech, focused on Development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store