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

Questions:

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:

classes1.dex
classes2.dex
classes3.dex

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:

classes.dex
|-- 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()
dexM.writeTo(File(classesDexFilePath))

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)

Sources:
DexMerger
DexBuffer
CollisionPolicy

Answer:

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.

Answer:

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.

Answer:

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.