在Android开发过程中,偶尔需要自己写一些脚本来优化构建步骤。比如修改版本号,生成JAR包等。
1. 关于task的Action与configuration的区别
gradle中任务执行一般分为三个阶段,分别是初始化,配置,和执行阶段。比如下面的一个脚本:
ext.employee = 'Miss Wang'
task greet(group:'android-developer', description:'i am new to android world.') {
logger.quiet "task config start!"
employee='Donald Trump'
logger.quiet "task config finished!"
doLast {
logger.quiet "task running"
println "hello, " + employee
}
}
doLast部分就是任务greet的Action部分,而doLast外面的,就是任务greet的配置部分。配置部分先于执行部分执行。
2. 实例:从配置文件中读取版本号
ext.versionFile = file('version.properties')
task loadVersion {
project.version = readVersion()
}
task hello << {
println 'version = $project.version'
}
MyProjectVersion readVersion() {
logger.quiet "Reading the version file"
if (!versionFile.exists()) {
throw new GradleException("Required version file does not exist:$versionFile.canonicalPath")
}
Properties versionProps = new Properties()
versionFile.withInputStream { stream ->
versionProps.load(stream)
}
new MyProjectVersion(versionProps.major.toInteger(), versionProps.minor.toInteger(),
versionProps.release.toBoolean())
}
class MyProjectVersion {
Integer major
Integer minor
Boolean release
MyProjectVersion(Integer major, Integer minor) {
this.major = major
this.minor = minor
this.release = Boolean.FALSE
}
MyProjectVersion(Integer major, Integer minor, Boolean release) {
this(major, minor)
this.release = release
}
@Override String toString() {
"$major.$minor${release ? '' : '-SNAPSHOT'}"
}
}
运行需要在根目录下建立version.properties文件,否则会抛出异常 Required version file does not exist。
3. 自定义任务
task generateConfigFile(type: GenerateUserConfigFile) {
userName 'Donald Trump'
major 'computer'
interest 'write'
destFile new File("hello.txt")
}
class GenerateUserConfigFile extends DefaultTask {
@Input
String userName
@Input
String major
@Input
String interest
@OutputFile
File destFile
GenerateUserConfigFile() { }
@TaskAction
void actionNow() {
ant.propertyfile(file:destFile){
entry(key: 'userName', type: 'string', operation: '=', value: userName)
entry(key: 'major', type: 'string', operation: '=', value: major)
entry(key: 'interest', type: 'string', operation: '=', value: interest)
}
}
}
执行./gradlew -q generateConfigFile即可生成配置文件hello.txt。
#Fri, 11 Nov 2016 22:14:53 +0800
userName=Donald Trump
major=computer
interest=write
4. 使用gradle自带的任务
task createFiles << {
def f1 = new File("hello1.txt")
def f2 = new File("hello2.txt")
f1.withObjectOutputStream { stream ->
stream << "hello,world."
}
f2.withObjectOutputStream { stream->
stream << "hello,android."
}
}
task zipTest(type:org.gradle.api.tasks.bundling.Zip, dependsOn: [createFiles]) {
logger.quiet "zip test now!"
delete 'hello.zip'
from(rootDir) {
include 'hello1.txt'
include 'hello2.txt'
}
archiveName 'hello.zip'
}