从AndroidManifest中通过正则获取属性值:
android.applicationVariants.all { variant ->
def manifestFile = file("src/main/AndroidManifest.xml")
def pattern = Pattern.compile("versionName=\"(.+)\"")
def manifestText = manifestFile.getText()
def matcher = pattern.matcher(manifestText)
matcher.find()
def versionName = matcher.group(1)
pattern = Pattern.compile("versionCode=\"(.+)\"")
matcher = pattern.matcher(manifestText)
matcher.find()
def versionCode = matcher.group(1)
}
还可以通过GPath库操作
def getVersionNameAdvanced(){
def xmlFile = project.file("AndroidManifest.xml")
def androidManifest = new XmlSlurper().parse(xmlFile)
//def androidManifest = new XmlSlurper().parse("AndroidManifest.xml")
return androidManifest['@android:versionName']
}
获取时间方法:
def buildTime() {
def df = new SimpleDateFormat("yyyyMMdd'-'HHmm")
df.setTimeZone(TimeZone.getDefault())
return df.format(new Date())
}
copy apk操作
task copyOutputApk(type: Copy) {
from 'build/outputs/apk'
into 'apk'
exclude '**/*-unaligned.apk'
}
project.tasks.findByName('assembleRelease') << {
copyOutputApk.execute()
clean.execute()//清除build文件夹
}
或者定义一个task依赖,执行gradlew allTask就行了
task allTask(dependsOn: ['clean', 'assembleRelease', 'copyOutputApk']){
clean.mustRunAfter copyOutputApk
copyOutputApk.mustRunAfter assembleRelease
}
删除unaligned apk
android.applicationVariants.all { variant ->
variant.assemble.doLast {
variant.outputs.each { output ->
println "aligned " + output.outputFile
println "unaligned " + output.packageApplication.outputFile
File file = output.packageApplication.outputFile;
if (variant.buildType.zipAlignEnabled && file.getName().contains("unaligned")) {
println "deleting " + file.getName()
file.delete()
}
}
}
}
//对于 android library 编译,我会 disable 所有的 debug 编译任务
def disableDebugBuild(){
//project.tasks 包含了所有的 tasks,下面的 findAll 是寻找那些名字中带 debug 的 Task。
//返回值保存到 targetTasks 容器中
def targetTasks = project.tasks.findAll{task ->
task.name.contains("Debug")
}
//对满足条件的 task,设置它为 disable。如此这般,这个 Task 就不会被执行
targetTasks.each{
println "disable debug task : ${it.name}"
it.setEnabled false
}
}