Android 包体积优化实战

看似尋常最奇崛,成如容易卻艱辛。北宋.王安石

  最近由于项目需要,做了一些削减包体积的工作,由于之前项目已经进行过包体积优化方面的工作,期待百尺竿头,更进一步。花了好大的功夫,最终包体积从 25.1M 到 24.5M , 看似只有简单的 600KB 。 但是,在此过程,也很开心,学到了很多新知识,下面简单就包体积优化方面的一些小知识分享一下。

一、 Minifying code

   启代码优化是一种最常用的压缩代码的方式,配合 proguard 文件的使用,可以有效的压缩代码的体积,由于开启混淆会销毁额外的编译时间以及 Debug 包的时候,难以定位问题,所以一般在 release 包的时候,启用代码优化,gradle配置如下:

android {
    ...
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

   proguard 文件可以根据代码需要,配置需要 keep 的类等工作,在此提供两个项目中常用的优化包体积小点。

  1.1 、Relase 包去除 Log 输出

   在 Release 包中,有没有一种方式可以直接去除开发者常用的 Log 操作语句呢,proguard 有为开发者提供了相对应的办法,assumenosideeffects , 官方对该关键词的解释如下:

Specifies methods that don't have any side effects (other than maybe returning a value). In the optimization step, 
ProGuard will then remove calls to such methods, if it can determine that the return values aren't used. ProGuard will 
analyze your program code to find such methods automatically. It will not analyze library code, for which this option can
 therefore be useful. For example, you could specify the method System.currentTimeMillis(), so that any idle calls to it will 
be removed. With some care, you can also use the option to remove logging code. Note that ProGuard applies the option 
to the entire hierarchy of the specified methods. Only applicable when optimizing. In general, making assumptions can be 
dangerous; you can easily break the processed code. Only use this option if you know what you're doing!

   简易翻译过来,关键解释如下 :
   指定没有任何副作用的方法(除了可能返回值)。 在优化步骤中,如果 ProGuard 可以确定不使用返回值,则会删除对此类方法的调用。 通过解释可以看到,编译过程中会自动帮助我们删除此类方法的调用,那么如何删除 Log 输出呢,代码如下:

# Remove logging in release build.
-assumenosideeffects class android.util.Log {
    public static boolean isLoggable(java.lang.String, int);
    public static int v(...);
    public static int i(...);
    public static int w(...);
    public static int d(...);
    public static int e(...);
}

   通过上述 proguard 的配置,可以轻松去除 Log 的调用。有效缩减包体积大小。

  1.2 、包依赖传递

   在日常开发中,有时候为了提高开发速度,会引入各种第三方库,而第三库又引入了其他的库,如果这条链很长,那么很容易增加包体积,通过 gradlew app:dependencies 可以方便查看项目的引用链,以自己项目为例,部分依赖显示如下:

|    \--- project :sub-libraries:integration:okhttp3
|         +--- com.squareup.okhttp3:okhttp:3.8.1
|         |    \--- com.squareup.okio:okio:1.13.0
|         +--- com.android.support:support-annotations:27.1.1
|         +--- com.github.bumptech.glide:glide:4.0.0 (*)
|         \--- project :sub-libraries:libhttp
|              +--- project :sub-libraries:CommonUtils (*)
|              +--- com.squareup.okhttp3:okhttp:3.8.1 (*)
|              +--- com.squareup.okhttp3:logging-interceptor:3.8.1
|              |    \--- com.squareup.okhttp3:okhttp:3.8.1 (*)
|              +--- com.google.code.gson:gson:2.8.0
|              +--- com.squareup.retrofit2:retrofit:2.3.0
|              |    \--- com.squareup.okhttp3:okhttp:3.8.0 -> 3.8.1 (*)
|              +--- com.squareup.retrofit2:adapter-rxjava2:2.3.0
|              |    +--- com.squareup.retrofit2:retrofit:2.3.0 (*)
|              |    \--- io.reactivex.rxjava2:rxjava:2.0.0 -> 2.1.1
|              |         \--- org.reactivestreams:reactive-streams:1.0.0
|              +--- com.squareup.retrofit2:converter-gson:2.3.0
|              |    +--- com.squareup.retrofit2:retrofit:2.3.0 (*)
|              |    \--- com.google.code.gson:gson:2.7 -> 2.8.0
|              +--- io.reactivex.rxjava2:rxandroid:2.0.1
|              |    \--- io.reactivex.rxjava2:rxjava:2.0.1 -> 2.1.1 (*)
|              \--- com.android.support:appcompat-v7:26.1.0 -> 27.1.1 (*)
+--- project :sub-libraries:libcocos2dx
|    +--- :lottie-release:
|    +--- com.android.support:appcompat-v7:27.1.1 (*)
|    \--- project :sub-libraries:CommonLib (*)
+--- project :sub-libraries:filedownloader
|    \--- project :sub-libraries:CommonLib (*)

  通过上述指令可以清楚看到项目所引用的各个库,那么这时候需要额外注意导入的第三方库引入了什么其他的库,如果项目有配置 product flavors ,如果只需要在固定的 flavor 里配置相对应的依赖。那么可以在 gradle 文件配置依赖的时候,加上对应的 product flavor 名称,比如项目 flavor 有 free 构建变体,那么可以配置如下

dependencies { freeCompile ‘…’ }.

  这样其他构建变体的包并不会将该依赖引入,有效的缩减了包体积的大小。

二、 Remove Unused Resource

   与第一步压缩代码不同的是,还有一种可以缩减包体积的方式就是删除无用资源,随着项目迭代,需要删除不用的 layout / drawable / image 等资源文件,为了保证这些资源文件可以正常的被删除,需要配置如下:

android {
    ...
    buildTypes {
        release {
            minifyEnabled true
            // 注 : 需要在此处开启 resshrink
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

  根据上述配置,系统在编译时可以自动检测无用的资源,但是 shrinkResources 有可能会错误的识别出可能正在被项目引用的资源文件,为了防止这种情况出现,可以使用 keep attribute 来告诉某些特定的资源不被移除,配置文件如下:

   res/raw/keep.xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
   tools:keep="@layout/l_used*_c,@layout/l_used_a,@layout/l_used_b*"
/>

   上述配置能帮助我们制定应该保证项目哪些资源不被删除,同样的,如果指定要删除一些特定的文件,那么可以使用 discard attribute , 配置如下:

   res/raw/keep.xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
    tools:shrinkMode="safe"
    tools:discard="@layout/unused2"
/>

   通常情况下,resources shrinker 都可以自动识别出有哪些资源正在被引用,但是,如果代码有类似 Resources.getIdentifier() 的调用,这意味着你的代码在寻找资源,这种资源名称基于动态生成的字符串。默认情况下,resources shrinker 会以防御性方式运行,并将具有匹配名称格式的所有资源标记为可能已使用且无法删除。
  例如,以下代码会将具有img_前缀的所有资源标记为已使用。

String name = String.format("img_%1d", angle + 1);
res = getResources().getIdentifier(name, "drawable", getPackageName());

   那么如何解决这种问题呢,上述是默认启用的安全删除模式的示例。 但是值得庆幸的是,系统提供了一种属性去关闭这种更安全的方式,并指定资源缩减器仅保留确定使用的资源。 为此,你需要在keep.xml 文件中将 shrinkMode 设置为 strict,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
    tools:shrinkMode="strict"
    />

   如果您确实启用了 strict mode ,并且您的代码也引用了动态生成字符串的资源,如上所示,那么您必须使用以下工具手动保留这些资源:keep attribute。
   值得注意的是,resources shrinker 并不会帮助我们在打包的过程中真正的去删掉这些无用的资源,它会自动的帮我们将图片、xml文件等进行替换成一个空文件,在编译完的 /build/outputs/mapping/resources.txt 文件中,可以查看到日志如下:

Skipped unused resource res/anim/abc_fade_in.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/anim/abc_fade_out.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/anim/abc_slide_in_bottom.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/anim/abc_slide_in_top.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/anim/abc_slide_out_bottom.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/anim/abc_slide_out_top.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/anim/intl_dialog_slide_in_from_top.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/animator/bubble_down_click_animator.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/animator/bubble_trash_hide_magnetism_animator.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/animator/bubble_trash_shown_magnetism_animator.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/animator/bubble_up_click_animator.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/color/abc_btn_colored_text_material.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/color/com_facebook_button_text_color.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/color/common_google_signin_btn_text_dark.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/color/common_google_signin_btn_text_light.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/color/common_google_signin_btn_tint.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/color-v23/abc_btn_colored_text_material.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/drawable-anydpi-v21/ic_icfun_icon_female_w.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/drawable-anydpi-v21/ic_icfun_icon_login_fb.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/drawable-anydpi-v21/ic_icfun_img_home_1v1bg_arrows.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/drawable-anydpi-v21/ic_icfun_pk_result_invited_arrow.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/drawable-anydpi-v21/ic_icfun_vs_icon_allgame.xml: -1 bytes (replaced with small dummy file of size 104 bytes)
Skipped unused resource res/drawable-anydpi-v21/ic_icfun_vs_icon_vs.xml: -1 bytes (replaced with small dummy file of size 104 bytes)

   通过对 resources.txt 文件的观察,可以查看项目中哪些资源并没有被引用,可以自己写一个脚本,轻松真正删除掉项目中没有被引用到的文件。
   删除无用资源是一种有效缩减包体积的方式,通过上述配置以及在项目中的实践,包体积缩小了 1.5M!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,548评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,497评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,990评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,618评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,618评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,246评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,819评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,725评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,268评论 1 320
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,356评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,488评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,181评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,862评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,331评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,445评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,897评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,500评论 2 359

推荐阅读更多精彩内容