Reputation: 41
As part of my build script, I would like to run some Java code before the APK is packaged.
When I try to build my project, I get the error:
Error: Could not find or load main class net.bgreco.myapp.build.BuildScript
BuildScript.java
is located in app/src/main/java/net/bgreco/myapp/build/
.
The BuildScript.class
does get compiled successfully before I receive the error message above, and I can run it from the command line with no errors.
app/build.gradle
:
task runBuildScript(type: JavaExec) {
main = 'net.bgreco.myapp.build.BuildScript'
}
tasks.whenTaskAdded { theTask ->
if (theTask.name.contains('package')) {
theTask.dependsOn 'runBuildScript'
}
}
Upvotes: 1
Views: 998
Reputation: 41
With some help from this answer, I got it working by modifying the classpath as below. I also needed to reference some of the Android libraries so I included the path to android.jar
.
app/build.gradle
:
task runBuildScript(type: JavaExec) {
String flavor, buildType
(flavor, buildType) = getCurrentFlavorAndBuildType()
classpath files("build/intermediates/classes/" + flavor + "/" + buildType, "${android.getSdkDirectory().getAbsolutePath()}\\platforms\\${android.compileSdkVersion}\\android.jar")
main = 'net.bgreco.myapp.build.BuildScript'
args = [flavor] // Not needed unless you want to know the current flavor from within the BuildScript
}
tasks.whenTaskAdded { theTask ->
if (theTask.name.contains('package')) {
theTask.dependsOn 'runBuildScript'
}
}
def getCurrentFlavorAndBuildType() {
Gradle gradle = getGradle()
String tskReqStr = gradle.getStartParameter().getTaskRequests().toString()
Pattern pattern;
if (tskReqStr.contains("assemble"))
pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")
else
pattern = Pattern.compile("generate(\\w+)(Release|Debug)")
Matcher matcher = pattern.matcher(tskReqStr)
if (matcher.find())
return [matcher.group(1).toLowerCase(), matcher.group(2).toLowerCase()]
else {
println "NO MATCH FOUND"
return ["", ""];
}
}
Upvotes: 1