在我的应用程序中,我使用 Assets 目录来存储一些 XML 文件(有些很大)。 在我的设计时,我希望文件使用缩进并在其中添加一些注释。 这会扩大我的 xml 文件,加起来会很大。
是否可以在 gradle 构建中添加一个任务,以在将 xml 文件打包到 apk 之前删除所有缩进和注释?如果是怎么办?
这不仅会缩小我的 apk,还会在运行时协助 xml 处理。
编辑
fhomovc 的回答是正确的,但遗漏了一些部分。 我会将其标记为正确,但如果其他人需要它,请提供详细信息:
一般来说,我需要一个运行 minify 实用程序的任务,它应该如下所示:
task minifyAssets(type:Exec) {
workingDir dirName // the directory of the merged assets under the build directory
commandLine 'minify', '-r', '-o', '.', '.'
doFirst {
println 'minifyAssets...'
}
}
该任务只应在合并 Assets 任务执行之后和打包任务执行之前执行。
主要问题是每个变体都应该有一个专门的任务,所以我需要动态地做:
首先创建exec任务,并使其依赖于merge任务
applicationVariants.all { variant ->
// dynamically add minify task for specific variant
def dirName = new File("app\\build\\intermediates\\merged_assets\\" + variant.name + "\\out\\levels").getAbsolutePath()
def minifyTaskName = "minifyAssets" + variant.name
def mergeAssetsTaskName = "merge" + variant.name + "Assets"
def myTask = tasks.register(minifyTaskName, Exec) {
workingDir dirName
// require that minify utility will be in the path. Download from https://github.com/tdewolff/minify/tree/master/cmd/minify
commandLine 'minify', '-r', '-o', '.', '.'
doFirst {
println 'minifyAssets...' + workingDir
}
}
// set the minify task dependant on the merge assets task
myTask.get().dependsOn mergeAssetsTaskName
}
现在我们需要让具体的打包任务依赖于minify任务:
// when the package task is added make it dependant on the minify task
tasks.whenTaskAdded { theTask ->
if (theTask.name.startsWith("package") && (theTask.name.endsWith("Debug") || theTask.name.endsWith("Release"))) {
def minifyTaskName = theTask.name.replace("package", "minifyAssets")
theTask.dependsOn minifyTaskName
}
}
最佳答案
您可以使用 xml 压缩器运行自定义脚本。
- 对于缩小器:你可以安装minify按照提供的安装步骤进行操作。
脚本:可以引用this answer .基本上你的任务看起来像这样
task executeScript(type:Exec) { println 'Minifying xmls...' //on linux commandLine 'minify -r -o ./ --match=\.xml ./values' // ./values should be the path to your resources directory }
查看文档以更好地了解 minify 的工作原理。我自己还没有测试过这个解决方案,所以它可能需要一些调整,但你已经明白了。如果您使用的是 Windows 机器,那么脚本 (commandLine
) 应该不同,如果我能在网上找到任何示例,我会添加它们。
关于android - 构建 apk 时如何减小 xml Assets 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58237704/