gradle android java groovy kotlin如今是扯不断,理也不乱了吧。现在大部分时间是写kotlin Android,以前是java,再以前都用的是eclipse呢。下面先记录一下gradle的日常操作
需求:测试要求打包的apk记录序列号,0 1 2 3的加,并且版本升级,自动从0开始,就像下面这样:
app_V4.71_0_gp.apk
app_V4.71_1_gp.apk
app_V4.71_2_gp.apk
........
app_V4.72_0_gp.apk
app_V4.72_1_gp.apk
这样命名的话,那么单从编译过程是无法获取到打包是第几次的,需要个全局的记录。可以通过生成缓存文件去记录是第几次打包。
这样做
android.applicationVariants.all { variant ->
print "type_______________" + "\n"//productFlavors * buildTypes 循环次数
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.apk')) {
def buildTypeName = variant.buildType.name
if (variant.productFlavors[0].name.endsWith("Lidow") && buildTypeName.equals("release")) {
def list = []
int lastVersion
int currentVersion
int currentVersionCodeIndex
new File("${variant.buildType.getSigningConfig().getStoreFile().getParent()}/singUp.properties").withReader('UTF-8') { reader ->
reader.eachLine {
if (it.contains('version_code_number')) {
lastVersion = Integer.parseInt(it.split(":")[1])
currentVersion = defaultConfig.versionCode
it = "version_code_number:${defaultConfig.versionCode}"
} else if (it.contains('version_code_index')) {
currentVersionCodeIndex = Integer.parseInt(it.split(":")[1])
if (currentVersion > lastVersion) {
currentVersionCodeIndex = 0;//从0开始
} else {
currentVersionCodeIndex = currentVersionCodeIndex + 1
}
it = "version_code_index:${currentVersionCodeIndex}"
}
list.add(it + "\n")
}
}
//然后写回去:
new File("${variant.buildType.getSigningConfig().getStoreFile().getParent()}/singUp.properties").withWriter('UTF-8') { writer ->
list.each {
writer.write(it)
}
}
def fileName = "${variant.productFlavors[0].name}_V${defaultConfig.versionName}_${currentVersionCodeIndex}_${buildTypeName}.apk"
output.outputFile = new File(outputFile.parent, fileName)
print "reName" + "\n";
} else {
print "ddddddd" + "\n";
delete(outputFile)
}
}
}
}
----------
其中singUp.properties就是一个普通文件,内容是这样的
version_code_number:23
version_code_index:0
分析,通过singUp.properties文件来记录信息,之后gradle加载读取,并进行逻辑判断,增加其他操作。我把该文件放在了签名文件的目录下,通过读取配置的签名文件路径,来获取该文件,不然得用电脑的绝对路径。这样的话,每个人的电脑路径就不一样了,统一不起来。
当然我们还能通过这样的缓存来定制其它的需求