# Building a dex file on gradle.

I needed to create a simple ''.dex'' file that was independent of the actual code I was doing. To achieve that on gradle here’s what you need:

1. Add a source path to a new sourceSet to the main project.

2. Create a "Jar" task to build a jar from the source.

3. Create a "exec" tast to dex the jar file.

4. Make the android build depend on the last task you created.

## New SourceSet

This is pretty much trivial. Just add a "sourceSet" section to the top level of the project.

To control the compilation will need to setup the task "compileNameJava" as shown on the example bellow.

sourceSet {
name {
java {
srcDir _PATH_
}
}
}

compileNameJava {
sourceCompatibility = 1.7
targetCompatibility = 1.7
}

## Jar task

You need to create a normal gradle task, once again at the top level. Use the "from" property to setup the source set that was added on the step before.

The generated jar will be named after the "sourceSet" name followed by the version. You may need change to setup the name of the created jar, to do this update the "baseName" property of the task. The version property controls the version, if that property is set to null the version will not be appended to the name. The sample bellow will create a jar file named "base_name.jar".

task createJar(type: Jar) {
from sourceSets.name.output
baseName "base_name"
version null
}

## Dex the jar.

Apparently new versions of the android plugin have made the Dex task private and inaccessible. So the way I found to this is to execute the 'dx' command directly. To do this correctly I found the SDk path being used on gradle and also the tool version to build the path to the command. Once I build this I can simply run the command.

task dexJar(type:Exec) {
dependsOn createJar

File output = file("build/outputs/new_dex")
output.mkdirs()
File dexExec = file(android.properties.sdkDirectory.absolutePath + "/build-tools/" + android.properties.buildToolsVersion + "/dx")
commandLine dexExec, '--dex', '--output=' + output + "/sauce.dex", 'build/libs'
}