Home » Android » android – Is there a way to merge two or more .dex files into one .dex file using Scala?

android – Is there a way to merge two or more .dex files into one .dex file using Scala?

Posted by: admin June 15, 2020 Leave a comment


I am doing some hacking on Jan Berkel’s SBT Android Plugin and I was wandering if there is a way to merge multiple .dex files into one .dex file that will contain all of them.

For example, if I have this:


Is there any way to merge them using Scala (in some acceptable time) to one single classes.dex file that will contain all 3 of them and have a following structure:

|-- classes1/...
|-- classes2/...
\-- classes3/...
How to&Answers:

OK, it seems I found something.

import com.android.dx.io.DexBuffer
import com.android.dx.DexMerger
import com.android.dx.merge.CollisionPolicy
val dexA = DexBuffer(File(classes1DexFilePath))
val dexB = DexBuffer(File(classes2DexFilePath))
val dexMerger = DexMerger(dexA, dexB, CollisionPolicy.FAIL)
val dexM = dexMerger.merge()

Could anyone verify this is indeed working?

Also, if this works, then merging more than 2 dex files should be the same as Max(Max(A, B), C), providing you write a method that with a prototype
DexBuffer merge(DexBuffer dexA, DexBuffer dexB)



I found a way which don’t need to compile from source, just use the SDK compiled jar.

java -cp dx.jar com.android.dx.merge.DexMerger output.dex input1.dex input2.dex

The dx.jar is located in Android SDK dir, like android\sdk\build-tools\26.0.2\lib. The dex file have 64k method limit, so it can’t hold so much in one dex file.


it’s working. r22 uses this way to pre-dex android-support-v4.jar and annotations.jar into dex format first. Ant then use dx.bat to merge them with the compiled .class files.


First zip them individually like classes1.dex.zip, classes2.dex.zip, classes3.dex.zip and then run following

java -jar dx.jar --dex --output=classes.dex.zip classes1.dex.zip classes2.dex.zip classes3.dex.zip

That’s it.
Now you have a classes.dex in classes.dex.zip with classes1.dex.zip classes2.dex.zip classes3.dex.zip are merged.