AndResGuard是微信的资源压缩工具,减少包体积大小的利器。
我们项目是在Jenkins上面构建的,所以是通过命令来执行的。我们直接来看代码
代码里面我有注释
/**
* 压缩APK
*/
def compress = {
name ->
//减去.apk
def path = name.substring(0, name.length() - 4)
def guardJarFile = file('./AndResGuard/AndResGuard-cli-1.2.15.jar')
def guardConfigFile = file('./AndResGuard/config.xml')
def originApkFile = file("./target/${name}")
def outputDir = file("./target/outapk")
def tempOutputDir = file("./target/tempoutapk")
//def patchTool = "$projectDir/patch/apkpatch-1.0.3/apkpatch.sh"
def zipPath
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
//patchTool = "$projectDir/patch/apkpatch-1.0.3/apkpatch.bat"
zipPath = file('./AndResGuard/7-Zip/7za')
} else {
zipPath = file('./AndResGuard/bin/7za')
}
def zipalignPath = file(System.getenv('ANDROID_HOME') + "/build-tools/${build_tools_version}/zipalign")
// 开始执行压缩命令
println "guardJarFile " + guardJarFile
println "zipPath " + zipPath
println "originApkFile " + originApkFile
println "ZipAlign apk, tools: " + zipalignPath.absolutePath
//主要就是这里,如果我们在这个地方直接加如-mapping命令的话是无效的(我的版本是1.2.15)
//不知道是Bug还是什么,所以最后我是在confing文件里面加的这个keepmaping
def proc = """java -jar ${guardJarFile} ${originApkFile} -config ${guardConfigFile}
-out ${tempOutputDir} -signature ${gKeyStore} ${gStorePass} ${gKeyPass} ${gAlias}
//-mapping ${maapingFilePath} 在这里加这句不生效
-7zip ${zipPath} -zipalign ${zipalignPath}""".execute()
proc.waitFor()
println "return code: ${proc.exitValue()}" + ", stderr: ${proc.err.text}" + " stdout: ${proc.in.text}"
//压缩后会清空目标文件夹,所以新建了tempOutputDir做为缓存目录,压缩成功后再复制到outputDir,
// 不然多包操作目标目录最后会只剩下最后的一个包
tempOutputDir.listFiles().each {
println "tempOutputDir:" + it
if (it.name.endsWith(".apk") || it.name.endsWith(".txt")) {
copyFile.call(it.getAbsolutePath(), outputDir.getAbsolutePath() + "/" + it.name)
}
}
}
最后的方案如下图,注意resource_mapping文件的路径:
至于resource_mapping.txt怎么在Jenkins上同步到Git仓库可以查看我另外的文章
Gradle(groovy)中执行Git命令,Jenkins构建后提交文件到Git仓库