背景
我们有个SDK module,常常有导出Jar包的需要 主要有以下需求
- 通过 createFullJarRelease 指令导出jar包,jar位置位于build/intermediates/full_jar/realse/full.jar
- 打出的jar包希望自动copy到工程的release目录下,便于查找
- 另外希望通过时间戳对jar包自动重命名
思路
- 在gradle中新建task -> exportJar
- 执行build
// task1.dependsOn(task2) 意味着执行task1前需要先执行task2
exportJar.dependsOn(deleteOldJar, build)
- 在build完成后执行createFullJarRelease
task finalize {
doLast {
System.out.println("execute createFullJarRelease")
createFullJarRelease.doTaskAction()
}
}
//build执行完后执行finalize task,只需要在doLast中执行createFullJarRelease即可
build.finalizedBy(finalize)
- 清空release目录下的文件
//遍历文件夹的文件全部清除,防止旧jar干扰新jar
task deleteOldJar(type: Delete) {
FileTree tree = fileTree("release")
tree.visit {
element -> delete element.file
}
}
- 把fullJar/release下的jar拷贝到release文件夹下并重命名
//拷贝jar,并用日期作为版本,用时分秒区分jar包防止没有生成
task exportJar(type: Copy) {
from('build/intermediates/full_jar/release/')
into('release/')
include('full.jar')
///Rename the jar
def calendar = Calendar.getInstance()
var year = calendar.get(Calendar.YEAR)
var month = calendar.get(Calendar.MONTH) + 1
var day = calendar.get(Calendar.DAY_OF_MONTH)
var sdf = new SimpleDateFormat("HHmmss")
var jarName = "sdk_v" + year + "." + month + "." + day + "_" +sdf.format(calendar.getTime()) + ".jar"
rename('full.jar', jarName)
}
执行task日志
代码
module的.gradle文件
///
task finalize {
doLast {
System.out.println("execute createFullJarRelease")
createFullJarRelease.doTaskAction()
}
}
build.finalizedBy(finalize)
task deleteOldJar(type: Delete) {
FileTree tree = fileTree("release")
tree.visit {
element -> delete element.file
}
}
//task to export contents as jar
task exportJar(type: Copy) {
from('build/intermediates/full_jar/release/')
into('release/')
include('full.jar')
///Rename the jar
def calendar = Calendar.getInstance()
var year = calendar.get(Calendar.YEAR)
var month = calendar.get(Calendar.MONTH) + 1
var day = calendar.get(Calendar.DAY_OF_MONTH)
var sdf = new SimpleDateFormat("HHmmss")
var jarName = "sdk_v" + (year - 2017) + "." + month + "." + day + "_" + sdf.format(calendar.getTime()) + ".jar"
rename('full.jar', jarName)
}
exportJar.dependsOn(deleteOldJar, build)
|