背景
公司项目目前处于收尾阶段,对APP的更改在于一些细节和逻辑的调试。因此准备对APK进行瘦身。
瘦身前
在未进行任何瘦身操作之前,APK的大小为22150 KB 左右,大概21.6M

瘦身开始
去除无用xml和图片
可以使用Android Studio自带的Lint,点击菜单栏 Analyze -> Run Inspection by Name -> unused resources -> Moudule ‘app’ -> OK,就可以查询到那些图片或者XML文件未被使用。

去除无用图片、XML后,apk大小为20.3
图片压缩
PuppyGo这个项目,主要是儿童亲子教育类型的,通过蓝牙控制机器狗进行相关的交互,主要是功能性的,图片还算多,未开始压缩前 xhdpi 和 xxhdpi两个文件的图片总共16.69M


图片压缩这里采用Tinypng,https://tinypng.com/,一次最多可压缩20张图片,不超过5M。或者可以花钱使用Pro版本,对图片数量没有限制

点击上图的压缩按钮,选择完图片,即可进行压缩,不用注册。

压缩完毕,点击Download ALL 即可下载得到压缩后的图片

压缩后两个文件夹总大小6.6M,下图压缩了11M,重新Build apk之后的安装包大小10.6m左右,相比之前的20.3M,压缩还是很可观的。


minifyEnabled混淆
在app的build.gradle设置minifyEnabled为True
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
同样的在app的proguard-rules.pro编写混淆规则,对自身项目的依赖库填写规则,例如greenDao,混淆后注意测试app各功能使用正常与否。
# greenDAO 3
-keep class org.greenrobot.greendao.**{*;}
-keepclassmembers class * extends org.greenrobot.greendao.AbstractDao {
public static java.lang.String TABLENAME;
}
-keep class **$Properties
设置shrinkResources
buildTypes {
release {
minifyEnabled true
shrinkResources true
}
}
删除未使用到代码
也是使用Android Studio的Lint,点击Analyze -> Run Inspection by Name ,输入 unused declaration ,然后选 Moudule ‘app’ -> OK,即可删除无用代码,我这里只缩小了15K左右。。。

设置resConfigs
PuppyGo项目分为中文版和另外的英文版,因此可以设置resConfigs只支持中文
android {
defaultConfig {
resConfigs "zh"
}
}
设置前的APK大小为9451 KB(9.22M),设置后为9370KB(9.14M),缩小了0.8M.
使用Webp格式图片
如果你没有用Tinypng等工具进行图片压缩,也可以用Android Studio自带的转Webp工具对图片进行格式转换,没有Convert to WebP这个选项的话,尝试更新Android Studio,图片位置右键,点击Convert to WebP


转换前大小为25KB,转换后为11.5KB.
最后
经过以上处理,APK大小由原来的21.6M,瘦身为9.14M(使用tinypng压缩),使用WebP格式的图片的话,apk大小为7.8M,进一步缩小。选择png压缩,还是转为WebP,自行选择。最后的结果相对来说,效果还是不错的,可以为用户节省一半的流量。当然,我的项目使用了两套图,如果只是用720P一套图,APK的大小将进一步缩小。
网友评论