cmoaciopm cmoaciopm -3 years ago 142
Android Question

How to add dependency jar files during compiling stage using gradle?

I build my

Android
application using
Gradle
.

The dependency jar files are retrieved during compiling stage and the path of these jar files are dynamic (because there is build number in the path, for example, /home/user1/workspace/myapp/libs/privatejar/build-1019/a.jar).

My gradle configue file looks like this.

apply plugin: 'android'

android {
compileSdkVersion 19
buildToolsVersion "19.1.0"

applicationVariants.all { variant ->
variant.javaCompile.dependsOn('GetJarUsingCompanyPrivateProtocol')
}
}

dependencies {
compile files('local/path/of/company/private/jar')
}

task GetJarUsingCompanyPrivateProtocol {
// This command will retrieve the jar
// into folder "local/path/of/company/private/jar"
commandLine 'get_jar_command'
}


Because the jar files do not exist before executing gradle compile command for the 1st time, it will always complain "Class * can not be found".
However, if I execute gradle compile for the 2nd time, it will work.

So I have two questions here:


  1. I have to change the local/path/of/company/private/jar every time when there is change to the build number of my jar files

  2. Is there any chance to make my gradle script work for the 1st time?



I know I can execute get_jar_command and then trigger
gradle
build, but it is annoying, can I achieve it in one shot?

Answer Source

I finally found solution by myself.

Gradle build has three distinct phases:

  1. Initialization
  2. Configuration
  3. Execution

The dependencies block will be executed during the configuration phase. So to use dependency jar in dependencies block, dependency jar must be download, either in initialization phase, or in configuration phase but before dependencies block execution.

In my case, initialization phase is not used. So I must ensure the dependency jar be downloaded before dependencies block. It's simply, adjusting the block sequence will be OK.

apply plugin: 'android'

android {
    compileSdkVersion 19
    buildToolsVersion "19.1.0"

    applicationVariants.all { variant ->
        variant.javaCompile.dependsOn('GetJarUsingCompanyPrivateProtocol')
    }
}

task GetJarUsingCompanyPrivateProtocol {
    // This command will retrieve the jar
    // into folder "local/path/of/company/private/jar"
    commandLine 'get_jar_command'
}

dependencies {
    compile files('local/path/of/company/private/jar')
}

Note: logic in doLast of task will be executed in execution phase. That's why I use

task GetJarUsingCompanyPrivateProtocol {
    commandLine 'get_jar_command'
}

Neither

task GetJarUsingCompanyPrivateProtocol {
    doLast {
        commandLine 'get_jar_command'
    }
}

nor

task GetJarUsingCompanyPrivateProtocol << {
    commandLine 'get_jar_command'
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download