对于缩小APk大小,除了开启混淆
minifyEnabled true
还有使用
shrinkResources true
说下这两者的区别
android { buildTypes { debug { minifyEnabled false shrinkResources false } release { minifyEnabled true shrinkResources true } } }
shrinkResources = true作用是删除无用的Resource,是与minifyEnabled 一起使用,minifyEnabled =true是开启混淆。
同样的资源代码
1.只有minififyEnable false 或者 minififyEnable false && shrinkResources true
APK大小为1.39M
资源文件和layout都存在且是有内容的
2.只有minifyEnable true
866K
资源文件和layout都存在且是有内容的
3.minifyEnable true && shrinkResources true
资源文件在但是没有内容大小都变成67字节,layout文件内容被清空
4.minifyEnable true && shrinkResources true 在res/raw/keep.xml(避免被误删除)写了配置的
<?xml version="1.0" encoding="utf-8"?> <resources xmlns:tools="http://schemas.android.com/tools" tools:keep="@layout/activity_four,@drawable/no_reference_but_keep"/>
没有在配置文件中声明保存的文件没有内容,声明保存的文件有内容(资源文件和layout文件)
注意:string.xml中没有被引用的怎么设置都不会被删除
可以通过gradlew clean assembleRelease - info来获得APK缩减资源的概览
当您压缩资源时,Gradle Console 会显示它从应用软件包中移除的资源的摘要。例如:
:android:shrinkDebugResources Removed unused resources: Binary resource data reduced from 2570KB to 1711KB: Removed 33% :android:validateDebugSigning
android 使用了shrinkResources = true后,有时候会出现问题。 最近项目集成阿里百川的意见反馈,添加的安全图片只是做验证,项目里面未引用。debug模式自然是没问题,因为shrinkResources 设置的是false,但在release 模式下,当shrinkResources = true的时候,集成的意见反馈出问题。
新增res/raw/keep.xml文件,在里面把需要保留的资源文件列举出
<?xml version="1.0" encoding="utf-8"?> <resources xmlns:tools="http://schemas.android.com/tools" tools:keep="@drawable/yw_1222"/>
如此问题就解决了。如果项目中需要keep多个资源可以tools:keep="@drawable/a,@layout/b,@layout/c"。意思就是在混淆的时候这些。
移动端产品功能的逐渐增加,apk包会越来越臃肿,这里面会存在大量的情况。,APP 的体积也不可避免地呈现上升趋势,如果不加以重视,几个版本迭代下来,可能你的 APP 体积会达到用户不能忍受的程度。比如冗余的代码、无用的资源、未合理化处理的图片等等。 所以Android APP瘦身是开发者必学的技术之一