Allows you to "five-off, killing six" easily into the manufacturers. Analogous to micro-letters, how to limit Apk be compressed on to the next big Android compression 8

This column focuses a large share knowledge Bat interview, follow-up will continue to update, like it trouble clicking a concern

github interview ↓ thematic links
about me

Interviewer: analogous to micro-letters, how to limit Apk be compressed on to the next big step 8 Android compression
(the interviewer is very focused on performance optimization, compression test job applicants whether they have the skills APK)

Job seekers: compression should start from every step of the compression process is essentially the process of squeezing toothpaste, squeeze step by step. The compression is divided into eight steps Apk

I. Introduction

With the continuous iteration of the project, the amount of code with the resource file continues to grow. APK file then there will be more and more packaged, if suddenly one day you call your boss or leader to optimize APK size, you do not know how to optimize it would not be justified, we will go together to analyze and optimize this article APK volume size of it.

II. Analysis of resource consumption APK

Note:
In the GitHub looking for a relatively high popularity of open-source projects, if required, they can click to download , try something yourself.

 

AS Build analysis tools directly used / Analyze APK

Draw assets> classes.dex> res> From the above figure lib where the resource files are taking up the most.

Here we take a look at how to reduce the size of it APK,

III. Optimization APK volume eight big step

1. convert the picture format webp

Webp concept

WebP is a lossy compression while providing lossless compression of image file format, derived from VP8 video encoding format. WebP originally released in 2010, aims to reduce the file size, but to achieve the same quality JEPG format images, hoping to reduce the transmission time of image files on the network. November 8, 2011, Google started to make WebP support lossless compression and transparent color function.

According to Google earlier test, WebP lossless compression less than 45 percent of the file size of the PNG file found on the network, even if they use PNG files in PNGCRUSH and PNGOUT treated, WebP still can reduce file size by 28%. For now, Webp can make an average 70% reduction in the size of the picture. WebP image format is the future trend of.

PNG / JPG to Webp

 

Click on the image file or folder, right-select Convert to Webp format, png / jpg picture compression format picture is webp

 

 

Finally, we only reduced by about less than 200 kb, it is possible to project images resources already not much, just too much due to the small picture.

Scenarios and advantages

  • Client software, embedded on the Chromium webview, this type of web browser application that can fully use the WebP format, enhance rendering speed load, regardless of compatibility.
  • Node-webkit program development, the volume can be reduced using WebP file package.
  • Mobile application or web games, the interface requires a lot of pictures, you can embed WebP Codec Pack, users can save traffic, improve access speed advantage:
  • For PNG images, WebP 45% smaller than PNG.

2. Remove multi-language

In the app / build.gradle add

{Android 
    ... 
    defaultConfig { 
        ... 
        // keep only English 
        resConfigs "EN" 
    } 
}

  

 

Here we find reduced about 200 kb

3. Remove unnecessary so library

Micro-channel version that decompile Android, micro-channel only fit the armeabi-v7a architecture, we support other libraries delete it.

android{
    ...
    defaultConfig{
        ...
            ndk {
            //设置支持的SO库架构
            abiFilters "armeabi-v7a"
     }
}
}

  

又优化了差不多 600 kb ,继续。

4. 去除无用资源 Link 检查(谨慎删除)

概念

Lint 是 Android Studio 提供的 代码扫描分析工具,它可以帮助我们发现代码结构 / 质量问题,同时提供一些解决方案,而且这个过程不需要我们手写测试用例。代码迭代版本一多,很容易会遗留一些无用的代码、资源文件,我们可以使用 Lint 进行清除。

怎么使用 Link 检查

打开 AS 工具,找到 Analyze > Run Inspection By Name > unused resources
优化


发现我们 link 大概优化了 700 kb继续。

 

注意
因为 link 是检查有没有引用来做的判断是否使用了资源,那么如果是这种方式勒,所以在删除的时候一定要谨慎

//动态获取资源 id , 未直接使用 R.xx.xx ,则这个 id 代表的资源会被认为没有使用过(类似不能混淆反射类)
int indetifier =getResources().getIdentifier("img_bubble_receive", "drawable", getPackageName()); getResources().getDrawable(indetifier);

  

5. 开启混淆

优化了大概 1.7M 继续

6.移除无用资源 shinkResource

  • 开启 shinkResource = true
 buildTypes {
        release {
            minifyEnabled true
            shrinkResources = true

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            shrinkResources = true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

  

这个有可能 link 删除了无用资源,所以没有在优化了

7.开启删除无用资源 (严格模式和普通模式) - 这个我这里就不可测试,你们下来可以测试下效果

普通模式也就是自定义模式

如果您有想要保留或舍弃的特定资源,请在您的项目中创建一个包含<resources> 标记的 XML 文件,并在tools:keep 属性中指定每个要保留的资源,在 tools:discard 属性中指定每个要舍弃的资源。这两个属性都接受逗号分隔的资源名称列表。您可以使用星号字符作为通配符

例如:

<?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*"
    tools:discard="@layout/unused2" />

  

将该文件保存在项目资源中,例如,保存在 res/raw/keep.xml。构建不会将该文件打包到 APK 之中。

指定要舍弃的资源可能看似愚蠢,因为您本可将它们删除,但在使用构建变体时,这样做可能很有用。例如,如果您明知给定资源表面上会在代码中使用(并因此不会被压缩器移除),但实际不会用于给定构建变体,就可以将所有资源放入公用项目目录,然后为每个构建变体创建一个不同的 keep.xml 文件。构建工具也可能无法根据需要正确识别资源,这是因为编译器会添加内联资源 ID,而资源分析器可能不知道真正引用的资源和恰巧具有相同值的代码中的整数值之间的差别。

严格模式

正常情况下,资源压缩器可准确判定系统是否使用了资源。不过,如果您的代码调用 Resources.getIdentifier()(或您的任何库进行了这一调用 - AppCompat 库会执行该调用),这就表示您的代码将根据动态生成的字符串查询资源名称。当您执行这一调用时,默认情况下资源压缩器会采取防御性行为,将所有具有匹配名称格式的资源标记为可能已使用,无法移除。

例如,以下代码会使所有带img_前缀的资源标记为已使用。

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

  

资源压缩器还会浏览代码以及各种res/raw/ 资源中的所有字符串常量,寻找格式类似于 file:///android_res/drawable//ic_plus_anim_016.png 的资源网址。如果它找到与其类似的字符串,或找到其他看似可用来构建与其类似的网址的字符串,则不会将它们移除。

这些是默认情况下启用的安全压缩模式的示例。但您可以停用这一“有备无患”处理方式,并指定资源压缩器只保留其确定已使用的资源。要执行此操作,请在keep.xml文件中将 shrinkMode 设置为strict,如下所示:

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

  

如果您确已启用严格压缩模式,并且代码也引用了包含动态生成字符串的资源(如上所示),则必须利用 tools:keep 属性手动保留这些资源。

8. AndResGuard 微信资源压缩方案

什么是 AndResGuard

AndResGuard 是一个缩小 APK 大小的工具,它的原理类似 Java Proguard ,但是只针对资源。它会将原本冗长的资源路径变短,例如将 res/drawable/wechat 变为 r/d/a。

为什么使用 AndResGuard

在以往的开发中,我们通常只混淆了代码,资源文件却暴露在他人面前,res 文件夹下所有文件名的可读性过强。

使用后的效果


AndResGuard 的配置

 

  • 项目根目录下 build.gradle 中,添加插件的依赖:
 dependencies {
        classpath 'com.tencent.mm:AndResGuard-gradle-plugin:1.2.16'
    }

  

  • 在 app 目录下,创建 and_res_guard.gradle 文件
apply plugin: 'AndResGuard'

andResGuard {
    mappingFile = null
    use7zip = true
    useSign = true
    keepRoot = false
    compressFilePattern = [
            "*.png",
            "*.jpg",
            "*.jpeg",
            "*.gif",
            "resources.arsc"
    ]
    whiteList = [
            // your icon
            "R.drawable.icon",
            // for fabric
            "R.string.com.crashlytics.*",
            // for umeng update
            "R.string.tb_*",
            "R.layout.tb_*",
            "R.drawable.tb_*",
            "R.drawable.u1*",
            "R.drawable.u2*",
            "R.color.tb_*",
            // umeng share for sina
            "R.drawable.sina*",
            // for google-services.json
            "R.string.google_app_id",
            "R.string.gcm_defaultSenderId",
            "R.string.default_web_client_id",
            "R.string.ga_trackingId",
            "R.string.firebase_database_url",
            "R.string.google_api_key",
            "R.string.google_crash_reporting_api_key",

            //友盟
            "R.string.umeng*",
            "R.string.UM*",
            "R.layout.umeng*",
            "R.drawable.umeng*",
            "R.id.umeng*",
            "R.anim.umeng*",
            "R.color.umeng*",
            "R.style.*UM*",
            "R.style.umeng*",

            //融云
            "R.drawable.u*",
            "R.drawable.rc_*",
            "R.string.rc_*",
            "R.layout.rc_*",
            "R.color.rc_*",
            "R.id.rc_*",
            "R.style.rc_*",
            "R.dimen.rc_*",
            "R.array.rc_*"
    ]

    sevenzip {
        artifact = 'com.tencent.mm:SevenZip:1.2.10'
    }
}

  

  • 在 app 模块下的 build.gradle 文件添加
apply from: 'and_res_guard.gradle'

  

  • 打包完之后效果图




    资源压缩了大概 1M

三. 总结

项目体积越大,资源越多,效果就越明显。
使用 Link 删除资源的话,一定要谨慎,提前做好备份。
咱们这里因为项目本身只有 22 M 多,最后优化了 4.5 M 下去。也还是很不容易的。

github面试↓专题链接
关于我

领取Android高级面试专题

非常希望和大家一起交流 , 共同进步

目前是一名程序员,不仅分享 Android开发相关知识,同时还分享技术人成长历程,包括个人总结,职场经验,面试经验等,希望能让你少走一点弯路。

Guess you like

Origin www.cnblogs.com/1157760522ch/p/11691183.html