在安卓Android Studio中,Gradle编译之后,如何在编译生成APK之后运行指令或者任务,例如复制apk文件到某个目录?
How to copy file to folder after Android Studio Gradle built / generated APK files?
网络上很多讨论,例如用
task finalize << {
println('finally!')
}
build.finalizedBy(finalize)
也有用这个方法的:
afterEvaluate {
}
用assembleRelease.doLast {} 方法的,这些都没用,真正有用的方法是,修改app的build.gradle文件,在末尾添加下面类似的代码:
gradle.buildFinished {
def buildtype = 0
exec {
def fn = "" + rootProject.projectDir + "/app/build/outputs/apk/debug/app-debug-${buildNumber}.apk"
File file = new File(fn)
if (!file.exists()) {
fn = "" + rootProject.projectDir + "/app/build/outputs/apk/release/app-release-${buildNumber}.apk";
file = new File(fn)
buildtype = file.exists() ? 1 : 0
}
if (file.exists()) {
fn = fn.replace("/", "\\")
commandLine "cmd", "/c", "copy /y ${fn} ..\\app.apk"
} else
commandLine "echo", "APK file not found"
}
// 只在Release的时候才发布到服务器
if (buildtype == 1) {
exec {
workingDir rootProject.projectDir
commandLine "ftp", "-i", "-s:ftp.txt", ">nul"
}
}
}
上面的方法有些BUG,比如buildNumber长得太快,如果真的想要做到在某些任务完成时处理某些动作,可以用下面的方法:
gradle.taskGraph.afterTask {
Task task,TaskState state ->
if (!state.failure) {
if ("$task.name" == "assembleRelease") { // <-----------只在 assembleRelease 任务成功后运行
def fn = "" + rootProject.projectDir + "/app/build/outputs/apk/release/Camera-release-${buildNumber}.apk"
File file = new File(fn)
if (file.exists()) {
fn = fn.replace("/", "\\")
exec { commandLine "cmd", "/c", "copy /y ${fn} ..\\Camera.apk" }
exec {
workingDir rootProject.projectDir
commandLine "ftp", "-i", "-s:ftp.txt", ">nul"
}
} else
println("APK 文件找不到!");
vb.write(buildNumber.toString());
}
}
}
自定义一个plugin,在plugin被应用的时候,新建一个task,并标记该task在assembleRelease之后执行
gradle的plugin使用这里不讲。
源码
Task diyTask = project.task('diyTask') {
doLast {
Utils.println("diy task run")
}
}
project.tasks.whenTaskAdded { Task theTask ->
if (theTask.name == 'assembleRelease') {
theTask.dependsOn(diyTask)
}
}
如果你想让自定义task在assembleRelease之前执行,需要计入一个mustRunAfter依赖
Task diyTask = project.task('diyTask') {
doLast {
Utils.println("diy task run")
}
}
project.tasks.whenTaskAdded { Task theTask ->
if (theTask.name == 'assembleRelease') {
theTask.dependsOn(diyTask)
theTask.mustRunAfter(diyTask)
}
}
---------------------
作者:良秋
来源:CSDN
原文:https://blog.csdn.net/a740169405/article/details/87814647
版权声明:本文为博主原创文章,转载请附上博文链接!