If you use and abuse of external libraries you may be confronted with a huge problem, a single Dalvik Executable (dex) file can only reference 65k methods. If that limit was exceed you will see something like this:

Conversion to Dalvik format failed:
Unable to execute dex: method ID not in [0, 0xffff]: 65536

or like this:

trouble writing output:
Too many field references: 131000; max is 65536.
You may try using --multi-dex option.

So, what can we do to workaround this problem? The answer is use ProGuard.

Proguard is a tool that enable shrink, optimize and obfuscate code. In our case what we need is the shrink option, it will remove the unused code, reducing the number of methods in dex.

On your gradle.build file add these:

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

Enabling ProGuard will solve the dex method limit issue but it will probably broke other things. For instance, If you use some 3rd-party-library that use java reflection to access some method, ProGuard will think that this method is not being used. To prevent that we have to add exceptions to our proguard rules file. Create a file named “proguard-rules.pro” and place it on the root of the project.

-dontobfuscate

-keep class net.fredericosilva.** { *;}

########################
#ButterKnife Exceptions#
########################

-keep class butterknife.** { *; }
-dontwarn butterknife.internal.**
-keep class **$$ViewBinder { *; }

-keepclasseswithmembernames class * {
    @butterknife.* <fields>;
}

-keepclasseswithmembernames class * {
    @butterknife.* <methods>;
}
#########################

As shown above, we are telling ProGuard to don’t obfuscate code(cause it’s not the point) and to don’t touch any of my code. Finally, as example I add exceptions to ButterKnife library (When it’s needed, libraries documentation will tell you what to add to your proguard rules, as you can see on ButterKnife doc).

HOW TO CHECK METHOD COUNT?

There are several ways to count the number of methods, one easy way to check it is use this simple tool:
http://inloop.github.io/apk-method-count/

Hope it helps…

Frederico Silva

Software Engineer

fredericojssilva fredericojss


Published