Sunday, August 24, 2014

Count dex methods for Android depedencies

When you see the error below you encounter the frustrating limit of Android build tool that it allows maximally 64K methods included in one dex file.

dex java.lang.IllegalArgumentException: method ID not in [0, 0xffff]: 65536

Below is a script that helps count out the methods of all jar files which will be weaved into the dex file. Then you can try to exclude some unnecessary libs to dehydrate the apk. If it’s still too big you must consider to give up using some of the libs or go with multiple dex files.

totalmethods=0
for jar in `find . -type f -name "*.jar"`; do
echo $jar
dx --dex --output=temp.dex $jar 2> /dev/null
jarmethods=$(cat temp.dex | head -c 92 | tail -c 4 | hexdump -e '1/4 "%d\n"')
echo $jarmethods
totalmethods=$(($jarmethods+$totalmethods))
echo $totalmethods
done

How to run it:
1. Find the folder containing all the jars required by the APK. The path for me(my Android build tools is 20.0.0) is
Android Project/build/intermediates/pre-dexed/debug
2. Create a file and copy the scripts above into the file – say call it “countdex.sh"
3. In the same folder, run the command below
sh counted.sh