Android gradle 脚本配置<二>

AndroidStudiogradle脚本高级api应用。

全局变量

1
2
3
4
5
6
7
8
path : :app
rootDir : XYSP
buildDir : XYSP/gradle-build/app
project.rootDir.absolutePath : XYSP
rootProject.buildDir : XYSP/gradle-build
rootProject.getRootDir().getAbsolutePath() : XYSP

执行 gradlew app:assembleDebug 命令输出。

任务监视tasks.whenTaskAdded

1
2
3
4
5
6
7
8
9
10
11
android {
tasks.whenTaskAdded { task ->
task.doFirst {
println("do task begin")
}
task.doLast {
println(task.name)
println("do task end")
}
}
}

当执行某一个任务的时候,会执行该监视器。

变量定义

1
2
3
4
5
def testCompile = {
println("testCompile...")
}
testCompile()

当每次执行某一个任务时,都会执行testCompile任务。

task定义

1
2
3
4
5
6
7
8
9
10
task taskSeq() {
doFirst {
println("begin......")
}
println('.................')
//
doLast {
println("end......")
}
}

copy命令

1
2
3
4
5
6
7
8
9
10
11
12
copy {
from "$project.rootDir.absolutePath/_docs/audio/f1.md", "$project.rootDir.absolutePath/_docs/audio/f2.md"
into "$project.rootDir.absolutePath/_docs/"
}
copy {
from project.rootDir.absolutePath + "/pathXXX/base.apk"
into project.rootDir.absolutePath + "/pathXXX/newDir"
rename {
"base2.apk"
}
}

将一个文件或者多个文件copy到另外某个目录。

File文件操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 删除目录,删除文件。。。
File file = new File(rootProject.getRootDir().getAbsolutePath(), "_logs")
if (file.exists()) {
file.deleteDir()
}
// 遍历目录
new File(project.rootDir.absolutePath + "/ctstest/").eachFileRecurse{ file ->
println(file)
}
// 创建目录
def newPath = project.rootDir.absolutePath + "/ctstest/libs/newDir"
mkdir(newPath)
// 重命名
def flavorFile = new File(project.rootDir.absolutePath + "/ctstest/libs/base.apk")
flavorFile.renameTo(newPath + "/base.apk")

全局定义

1
2
3
4
5
6
7
# settings.gradle
def initMagicEnv() {
gradle.ext.useMock = false
}
initMagicEnv()

BuildConfig

1
2
3
4
5
6
7
8
9
10
android {
defaultConfig {
multiDexEnabled true
ndk {
abiFilters 'armeabi-v7a'
}
buildConfigField("String", "CID", "\"abcde\"")
buildConfigField("int", "PID", "1704")
}
}

BuildConfig.java文件中会生成对应的CID常量和PID常量。

gradlew执行任务

1
2
3
4
5
6
gradlew myInstall
// 执行指定的Module下的task
gradlew app1:installDebug
gradlew app2:installDebug
gradlew uninstallDebug

LinkedList

1
2
3
4
def cmdList = new LinkedList<String>()
cmdList.add("java")
cmdList.add("-version")
cmdList.toArray()

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
task justInstall(type: Exec, dependsOn: 'assembleDebug') {
def installCmd = ["adb", "install", "-r", "$project.rootDir.absolutePath/pathXX/app.apk"]
commandLine installCmd
}
task mkLib(type: Exec) {
def mklibCmd = ["adb", "shell", "mkdir", "/data/data/packageName/lib/"]
commandLine mklibCmd
}
task myInstall(type: Exec, dependsOn: ['justInstall', 'mkLib']) {
def shellCmd = ["adb", "shell", "cp", "-r", "/sdcard/pathXX/lib/*", "/data/data/packageName/lib/"]
commandLine shellCmd
}