Android关于Groovy脚本执行ADB命令
项目使用场景:
项目中存在经常需要往设备中拷贝文件和数据库文件的操作,为便于提高开发效率,使用Groovy脚本编写一段脚本提高开发效率,省去那些繁琐的复制粘贴工作。
方法封装:
几个常用的方法封装:
/** 将AllProject项目目录下的 Data 数据库文件Push到设备中 **/
def A_PushDBToPDA(projectName) {
def rootProjectPath = rootProject.projectDir.path + File.separator + ‘AllProject’ + File.separator + projectName + File.separator
def PDASDCardPath = ‘ /sdcard/目录名称/’
//push前先移除对应的文件夹
task deleteDBDir {
doLast {
//定义adb命令并执行
def deleteDBDirCommand = ‘adb shell cd /sdcard && rm -r ‘ + PDASDCardPath + ‘Data’
Process deleteDBDirCommandProcess = deleteDBDirCommand.execute()
println “Success execute Command: ${deleteDBDirCommand.toString().readLines()}”
deleteDBDirCommandProcess.in.eachLine { processing ->
println processing
}
}
}
//执行该任务前先执行deleteDBDir目录
task A_PushDBToPDA(dependsOn: deleteDBDir) {
doLast {
def fromPath = rootProjectPath + ‘Data’
def adbCommand = ‘adb push ‘ + fromPath + PDASDCardPath
Process process = adbCommand.execute()
println “Success execute Command: ${adbCommand.toString().readLines()}”
process.in.eachLine { processing ->
println processing
}
}
}
}
使用ADB命令
删除sdcard下指定文件名或目录
adb shell cd /sdcard && rm -r 文件名称/目录
Push文件或目录到sdcard(注意空格)
adb push <从何处> <到哪里>
/** 将AllProject下的项目打包zip到 asserts 目录下,方便打包 **/
def A_AllProjectZipToAssets(projectName) {
//Gradle Zip文档 https://docs.gradle.org/current/dsl/org.gradle.api.tasks.bundling.Zip.html
def resProjectPath = rootProject.projectDir.path + File.separator + ‘AllProject’ + File.separator + projectName
def targetPath = project.projectDir.path + File.separator + ‘src’ + File.separator + ‘main’ + File.separator + ‘assets’
//println ‘from:’ + resProjectPath
//println ‘target:’ + targetPath
//打包前需先删除zip文件
task deleteExistedZip(type: Delete) {
delete targetPath + File.separator + projectName + ‘.zip’
}
//注:exclude可以忽略掉不需要打包的文件或目录
task A_AllProjectZipToAssets(type: Zip, dependsOn: deleteExistedZip) {
from resProjectPath
exclude(‘CNG.xml’, ‘Data’)//忽略CNG.xml文件和Data目录
destinationDir file(targetPath)
baseName projectName
appendix ” //The appendix part of the archive name, if any.
version ” //The version part of the archive name, if any. eg:FeiHe-1.0.0.zip
//extension ‘zip’ //The extension part of the archive name. Default is zip
classifier ” //The classifier part of the archive name, if any.
}
//tasks.A_AllProjectZipToAssets.dependsOn(deleteExistedZip)
}
具体使用:
这里就是Gradle文件的引用问题了,可以将gradle文件单独存放在项目的某个目录下,然后进行引用,例如
在项目根目录下创建目录:GradleConfig,将gradle文件放入,在app module下的build.gradle中引入即可:
apply from: rootProject.projectDir.path + ‘/GradleConfig/SyncOrPushFile.gradle’
构建为完成后,会在侧边的Gradle栏目中执行自定义的Task任务,如图: