android - 构建我的 apk 时如何减小 xml 资产的大小
问题描述
在我的应用程序中,我使用资产目录来存储一些 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...'
}
}
该任务只能在合并资产任务执行后、打包任务执行前执行。
主要问题是每个变体都应该有一个专门的任务,所以我需要动态地完成它:
首先创建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 minifier 运行自定义脚本。
- 对于 minifier:您可以按照提供的安装步骤安装minify 。
对于脚本:你可以参考这个答案。基本上你的任务看起来像这样
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 }
Check the documentation to understand better how minify works. I haven't tested this solution myself, so it may need a few adjustments but you get the general idea. If you are using a Windows machine then the Script (commandLine
) should be different, if I can find any examples online I'll add them.
推荐阅读
- python - 使用 Python 和 NetFilterQueue 进行 DNS 欺骗
- node.js - socket.io 无法在 React 应用上的 Heroku 上运行
- java - 配置 Springboot Jaeger 和 RSocket
- json - 使用 jq 通过非唯一键将数组转换为对象
- scala - Scala 中 Derived DataFrame 的持久化工作原理及其对性能的影响
- reactjs - 反应路由器循环并返回
- python - 使用部分文本获取标签的值
- ios - 每场比赛的游戏中心排行榜
- assembly - nasm 键盘驱动程序 I/O
- vuetify.js - 如何使用 Vuetify 将 v-card 放在页面中心