├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── hm │ │ └── iou │ │ └── thinapk │ │ └── demo │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── hm │ │ │ └── iou │ │ │ └── thinapk │ │ │ └── demo │ │ │ └── MainActivity.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── hm │ └── iou │ └── thinapk │ └── demo │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library1 ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── hm │ │ └── library1 │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── hm │ │ │ └── library1 │ │ │ ├── LibTest1Activity.java │ │ │ └── test │ │ │ └── LibTest2Activity.java │ └── res │ │ ├── layout │ │ └── activity_library_test1.xml │ │ └── values │ │ └── strings.xml │ └── test │ └── java │ └── com │ └── hm │ └── library1 │ └── ExampleUnitTest.java ├── plugin ├── .gitignore ├── build.gradle └── src │ └── main │ ├── groovy │ └── com │ │ └── hm │ │ └── iou │ │ └── thinapk │ │ └── plugin │ │ ├── RClassUtil.groovy │ │ ├── ThinApkPlugin.groovy │ │ ├── ThinApkRExtension.groovy │ │ └── ThinApkRTransform.groovy │ └── resources │ └── META-INF │ └── gradle-plugins │ └── com.hm.plugin.thinapk.properties └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | /.idea 11 | /app/keystore 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### 1. 前言 2 | 3 | 记得早期刚开始做 Android 开发的时候,一个 Android 应用也就几兆的大小。到现在,一个 APP少说十几兆,大则好几十兆甚至上百兆。所以针对 apk 包的瘦身问题,摆在了所有开发者的面前。毕竟安装包越小,下载安装肯定也就更快,对 APP 的运营也是有帮助的。网上已经有很多关于这方面的文章了,但是很多都泛泛而谈,道理大家都懂,但是怎么实操确不清楚。所以,本人计划将实际项目中用到的方案写出来,剖析剖析原理,一是给自己做个总结,二是给有需要的人做个参考,共同交流进步。 4 | 5 | ### 2. R.java 文件结构 6 | 7 | 众所周知,R.java 是自动生成的,它包含了应用内所有资源的名称到数值的映射关系。先创建一个最简单的工程,看看 R.java 文件的内容: 8 | 9 | ![R.java文件结构](https://upload-images.jianshu.io/upload_images/5955727-556ac6afce8e0d8c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 10 | 11 | 从图中可以看到,R.java 内部包含了很多内部类:如 layout、mipmap、drawable、string、id 等等,这些内部类里面只有 2 种数据类型的字段: 12 | 13 | ``` 14 | public static final int 15 | public static final int[] 16 | ``` 17 | 18 | 这里面,只有 styleable 最为特殊,只有它里面有 **public static final int[]** 类型的字段定义,其它都只有 **int** 类型的字段。 19 | 20 | ``` 21 | public static final class styleable { 22 | ... 23 | public static final int[] ActionBarLayout = new int[]{16842931}; 24 | public static final int ActionBarLayout_android_layout_gravity = 0; 25 | ... 26 | } 27 | 28 | ``` 29 | 30 | 此外,我们发现 R.java 类的代码行数有 1800 多行了,这还只是一个简单的工程,压根没有任何业务逻辑。如果我们采用组件化开发或者在工程里创建多个 module ,你会发现在每个模块的包名下都会生成一个 R.java 文件。以我的实际项目为例,我们采用组件化开发的架构,一个 APP 由将近 30 个组件组成,编译时则会生成将近 30 个 R.java 文件,算上业务逻辑里的资源 id ,平均每个 R.java 算 3000 行代码的话,则总共有 90000 行的代码,当然这只是一个很笼统的估计。 31 | 32 | ### 3.为什么R文件可以删除 33 | 所有的 R.java 里定义的都是常量值,以 Activity 为例: 34 | 35 | ``` 36 | public class MainActivity extends AppCompatActivity { 37 | 38 | protected void onCreate(Bundle savedInstanceState) { 39 | super.onCreate(savedInstanceState); 40 | setContentView(R.layout.activity_main); 41 | } 42 | 43 | } 44 | ``` 45 | 46 | R.layout.activity_main 实际上对应的是一个 int 型的常量值,那么如果我们编译打包时,将所有这些对 R 类的引用直接替换成常量值,效果也是一样的,那么 R.java 类在 apk 包里就是冗余的了。 47 | 48 | 前面说过 R.java 类里有2种数据类型,一种是 **static final int** 类型的,这种常量在运行时是不会修改的,另一种是 **static final int[]** 类型的,虽然它也是常量,但它是一个数组类型,并不能直接删除替换,所以打包进 apk 的 R 文件中,理论上除了 **static final int[]** 类型的字段,其他都可以全部删除掉。以上面这个为例:我们需要做的是编译时将 setContentView(R.layout.activity_main) 替换成: 49 | 50 | ``` 51 | setContentView(213196283); 52 | ``` 53 | 54 | ###4. ProGuard对R文件的混淆 55 | 通常我们会采用 ProGuard 进行混淆,你会发现混淆也能删除很多 R$*.class,但是混淆会造成一个问题:混淆后不能通过反射来获取资源了。现在很多应用或者SDK里都有通过反射调用来获取资源,比如大家最常用的统计SDK友盟统计、友盟分享等,就要求 R 文件不能混淆掉,否则会报错,所以我们常用的做法是开启混淆,但 keep 住 R 文件,在 proguard 配置文件中增加如下配置: 56 | 57 | ``` 58 | -keep class **.R$* { 59 | *; 60 | } 61 | -dontwarn **.R$* 62 | -dontwarn **.R 63 | ``` 64 | 65 | 那么接下来,我们讲讲如何删除所有 R 文件里的冗余字段。 66 | 67 | ### 4. 开发思路 68 | 具体的目标知道了,那怎么去实现呢,先说说我的思路: 69 | 70 | 1. 在打包 apk 编译时找到所有的 R$*.class ; 71 | 2. 收集所有 R$*.class 里的 public static final int 字段信息,将键值对缓存起来; 72 | 3. 遍历所有的 class,如果是 R.class,则删除里面的 public static final int 字段,但是需要保留 R$styleable.class 里的 public static final int[] 字段; 73 | 4. 如果不是 R$*.class ,则遍历该 class 里所有引用的静态字段,如果有对 R 文件里的静态字段引用,则根据前面缓存的键值对将其替换成对应的常量 int 值; 74 | 75 | 为了实现这个目标,我们需要创建一个 Gralde Plugin,在编译打包时能直接帮我们完成。这里需要用到2个技术:其一是 Gradle Transform,它能够在项目构建阶段即由 class 到 dex 转换期间,让开发者修改 class 文件;其二是 ASM 技术,它能让我们直接操作修改 class 文件。 76 | 77 | ### 5.R文件瘦身插件实操 78 | 79 | 这里提取出几个主要步骤来讲讲,具体代码已经开源。 80 | 81 | 怎么判断某个 class 文件是否为 R\$*.class ,主要是通过 class 的文件名来判断,然后通过 ASM 技术来读取 R$\*.class 里的所有 int 字段: 82 | 83 | ``` 84 | /** 85 | * 收集所有 R.class 及其内部类里的 int 常量字段信息 86 | * 存储的 key = class全路径类名 + 字段名,value = 该字段的常量值 87 | */ 88 | static Map mRInfoMap = new HashMap<>() 89 | 90 | /** 91 | * 收集R类相关信息,将所有 R.class 类里的 int 常量值缓存起来 92 | * 93 | * @param file class文件 94 | */ 95 | static void collectRInfo(File file) { 96 | if (!isRClass(file.absolutePath)) { 97 | return 98 | } 99 | def fullClassName = getFullClassName(file.getAbsolutePath()) 100 | println "需要收集的R类信息:fullClassName = ${fullClassName}" 101 | new FileInputStream(file).withStream { InputStream is -> 102 | ClassReader classReader = new ClassReader(is) 103 | ClassVisitor classVisitor = new ClassVisitor(Opcodes.ASM5) { 104 | @Override 105 | FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { 106 | if (value instanceof Integer) { 107 | //遍历读取所有 R.class 里的 int 常量值,例如 com/hm/library1/R$mipmap.class 里的 ic_launcher 常量值, 108 | //存储时存为 "com/hm/library1/R$mipmapic_launcher" = *** 109 | mRInfoMap.put(fullClassName - ".class" + name, value) 110 | } 111 | return super.visitField(access, name, desc, signature, value) 112 | } 113 | } 114 | classReader.accept(classVisitor, 0) 115 | } 116 | } 117 | 118 | /** 119 | * 判断该 class 文件是否是 R.class 类,及其内部类如 R$id.class 120 | * 121 | * @param classFilePath class文件的全路径名,例如:/Users/hjy/Desktop/app/build/intermediates/classes/debug/com/hm/library1/R.class 122 | * @return 如果是R.class及其它内部类class则返回true,否则返回false 123 | */ 124 | static boolean isRClass(String classFilePath) { 125 | classFilePath ==~ '''.*/R\\$.*\\.class|.*/R\\.class''' 126 | } 127 | 128 | /** 129 | * 判断该 class 文件是否是 R.class 类,及其内部类如 R$id.class,但是 R$styleable.class 类排除在外 130 | * 131 | * @param classFilePath 132 | * @return 133 | */ 134 | static boolean isRFileExceptStyleable(String classFilePath) { 135 | classFilePath ==~ '''.*/R\\$(?!styleable).*?\\.class|.*/R\\.class''' 136 | } 137 | 138 | /** 139 | * 从形如 /Users/hjy/Desktop/heima/code/gitlab/HM-ThinApk/app/build/intermediates/classes/debug/com/hm/library1/R.class 的类路径中截取出 com/hm/library1/R.class 140 | * 不管是当前工程的代码,还是远程依赖的aar包,在打包编译时,都会在工程的 app/build/intermediates/classes 路径下生成一系列R.class文件, 141 | * 根据打包模式是 debug 还是 release来区分,从中可以截取出 R.class 的包名了。 142 | * 143 | * @param filePath class文件全路径 144 | * @return 返回类似 "com/hm/library1/R.class"、"com/hm/library1/R$mipmap.class",其实就是类的全路径class名 145 | */ 146 | static String getFullClassName(String filePath) { 147 | String mode = "/debug/" 148 | int index = filePath.indexOf(mode) 149 | if (index == -1) { 150 | mode = "/release/" 151 | index = filePath.indexOf(mode) 152 | } 153 | return filePath.substring(index) - "${mode}" 154 | } 155 | 156 | ``` 157 | 158 | 159 | 在 Android 的 Transform 阶段,我们能读取到所有的 class 文件和 jar 包,那么 R$\*.class 是在文件目录里还是在 jar 包里呢?Android Studio编译时,会重新生成所有不同包名下的 R$\*.class,所有我们不需要遍历 jar 包来查找 R$*.class 文件,只需要遍历 class 文件即可,Transform类里的大致代码如下: 160 | 161 | ``` 162 | @Override 163 | void transform(Context context, Collection inputs, Collection referencedInputs, TransformOutputProvider outputProvider, boolean isIncremental) throws IOException, TransformException, InterruptedException { 164 | inputs.each { TransformInput input -> 165 | //第一次循环,只是为了收集 R.java 类信息 166 | input.directoryInputs.each { DirectoryInput directoryInput -> 167 | if (directoryInput.file.isDirectory()) { 168 | directoryInput.file.eachFileRecurse { File file -> 169 | if (file.isFile()) { 170 | //收集R.java类的信息 171 | collectRInfo(file) 172 | } 173 | } 174 | } else { 175 | //收集R.java类的信息 176 | collectRInfo(directoryInput.file) 177 | } 178 | } 179 | 180 | } 181 | ...... 182 | } 183 | ``` 184 | 185 | 通过这种方式可以收集到所有 R.class 文件,接下来我们需要二次遍历所有的 class 文件和 jar 包,这次需要删除 R.class 以及替换对 R.class 的直接引用。 186 | 187 | ``` 188 | /** 189 | * 将所有对 R.class 有引用的代码,直接替换成 int 值,这样在其他类里就不会内联 R.class 了, 190 | * R.class 存不存在就不会影响编译运行了 191 | * 192 | * @param bytes 193 | * @return 194 | */ 195 | private static byte[] replaceRInfo(byte[] bytes) { 196 | ClassReader classReader = new ClassReader(bytes) 197 | ClassWriter classWriter = new ClassWriter(0) 198 | ClassVisitor classVisitor = new ClassVisitor(Opcodes.ASM5, classWriter) { 199 | 200 | @Override 201 | MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { 202 | def methodVisitor = super.visitMethod(access, name, desc, signature, exceptions) 203 | methodVisitor = new MethodVisitor(Opcodes.ASM5, methodVisitor) { 204 | @Override 205 | void visitFieldInsn(int opcode, String owner, String name1, String desc1) { 206 | String key = owner + name1 207 | Integer value = mRInfoMap.get(key) 208 | if (value != null) { 209 | println "替换对R.class的直接引用:${owner} - ${name1}" 210 | super.visitLdcInsn(value) 211 | } else { 212 | super.visitFieldInsn(opcode, owner, name1, desc1) 213 | } 214 | } 215 | } 216 | return methodVisitor 217 | } 218 | } 219 | classReader.accept(classVisitor, 0) 220 | return classWriter.toByteArray() 221 | } 222 | ``` 223 | 224 | 删除 jar 包中的 R.class 相关引用: 225 | 226 | ``` 227 | /** 228 | * 遍历 jar 文件里的所有 class,替换所有对 R.class 的直接引用 229 | * 230 | * @param srcJar jar文件 231 | */ 232 | static void replaceAndDeleteRInfoFromJar(File srcJar) { 233 | File newJar = new File(srcJar.getParentFile(), srcJar.name + ".tmp") 234 | JarFile jarFile = new JarFile(srcJar) 235 | 236 | new JarOutputStream(new FileOutputStream(newJar)).withStream { JarOutputStream jarOutputStream -> 237 | jarFile.entries().each { JarEntry entry -> 238 | jarFile.getInputStream(entry).withStream { InputStream inputStream -> 239 | ZipEntry zipEntry = new ZipEntry(entry.name) 240 | byte[] bytes = inputStream.bytes 241 | if (entry.name.endsWith(".class")) { 242 | bytes = replaceRInfo(bytes) 243 | } 244 | if (bytes != null) { 245 | jarOutputStream.putNextEntry(zipEntry) 246 | jarOutputStream.write(bytes) 247 | jarOutputStream.closeEntry() 248 | } 249 | } 250 | } 251 | } 252 | 253 | jarFile.close() 254 | srcJar.delete() 255 | newJar.renameTo(srcJar) 256 | } 257 | ``` 258 | 259 | 这样还是会有个弊端,如果删除了所有的 R$*.class 里的字段,某些资源通过反射调用依旧会失败,所以我们还是需要能通过配置来 keep 住某些字段。 260 | 261 | ### 6.资源keep 262 | 所有的代码已经开源,有兴趣的可以查看,里面会有更具体的注释:[Android R文件瘦身插件:源码地址](https://github.com/houjinyun/Android-ThinApk) 263 | 264 | 资源 keep 配置示例: 265 | 266 | ``` 267 | thinRConfig { 268 | keepInfo { 269 | demomipmap { 270 | keepRPackageName = "com.hm.iou.thinapk.demo" 271 | keepRClassName = "mipmap" 272 | keepResName = ["ic_launcher"] 273 | keepResNameReg = ["ic_launcher.*"] 274 | } 275 | librarystring { 276 | keepRPackageName = "com.hm.iou.library" 277 | keepRClassName = "string" 278 | keepResName = ["app_name"] 279 | keepResNameReg = [""] 280 | } 281 | } 282 | } 283 | ``` 284 | 上面这个配置,com.hm.iou.thinapk.demo.R.mipmap 类里名为 ic_launcher 的字段不会被删除,com.hm.iou.library.R.string 类里名为 app_name 的字段不会被删除。 285 | 286 | * keepRPackageName:表示 R 文件所在的包名; 287 | * keepRClassName:表示 R 文件里的内部类名,如mipmap、string、id、drawable、layout 等等; 288 | * keepResName:要 keep 的资源名,是个数组 289 | * keepResNameReg:要 keep 的资源名,这是个正则表达式,会根据正则来进行匹配; 290 | 291 | ### 7.小结 292 | 本插件对采用组件化方式开发方式的app,或者有大量资源id定义的app可能会有显著效果,以我自己的项目为例,采用该插件以后,apk包大小减小了差不多0.4M左右。对这2种情况除外的app,效果可能并不会那么显著。当然这种方案只是锦上添花而已,我们应用里少用几张图片,可能包大小就减小了很多。 293 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'com.jakewharton.butterknife' 3 | apply plugin: 'com.hm.plugin.thinapk' 4 | 5 | thinRConfig { 6 | keepInfo { 7 | mipmap { 8 | keepRPackageName = "com.hm.iou.thinapk.demo" 9 | keepRClassName = "mipmap" 10 | keepResName = ["ic_launcher"] 11 | keepResNameReg = ["ic_launcher.*"] 12 | } 13 | } 14 | } 15 | 16 | android { 17 | compileSdkVersion 26 18 | defaultConfig { 19 | applicationId "com.hm.iou.thinapk.demo" 20 | minSdkVersion 19 21 | targetSdkVersion 26 22 | versionCode 1 23 | versionName "1.0" 24 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 25 | } 26 | 27 | buildTypes { 28 | release { 29 | // 是否开启混淆 30 | minifyEnabled false 31 | // 混淆文件位置 32 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 33 | } 34 | } 35 | } 36 | 37 | dependencies { 38 | implementation fileTree(dir: 'libs', include: ['*.jar']) 39 | implementation 'com.android.support:appcompat-v7:26.1.0' 40 | implementation 'com.android.support.constraint:constraint-layout:1.1.3' 41 | testImplementation 'junit:junit:4.12' 42 | 43 | compile 'com.squareup.okhttp3:okhttp:3.8.1' 44 | 45 | compile 'com.jakewharton:butterknife:8.4.0' 46 | annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0' 47 | 48 | compile project(':library1') 49 | 50 | } 51 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | 23 | -dontwarn javax.annotation.** 24 | 25 | # Retrofit 26 | -keepattributes Signature, InnerClasses, EnclosingMethod 27 | -keepclassmembers,allowshrinking,allowobfuscation interface * { 28 | @retrofit2.http.* ; 29 | } 30 | -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement 31 | -dontwarn kotlin.Unit 32 | -dontwarn retrofit2.-KotlinExtensions 33 | 34 | # Retrolambda 35 | -dontwarn java.lang.invoke.* 36 | 37 | # okhttp 38 | -keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase 39 | -dontwarn org.codehaus.mojo.animal_sniffer.* 40 | -dontwarn okhttp3.internal.platform.ConscryptPlatform 41 | 42 | # 对于R(资源)下的所有类及其方法,都不混淆 43 | -keep class **.R$* { 44 | *; 45 | } 46 | 47 | 48 | -dontwarn **.R$* 49 | -dontwarn **.R 50 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/hm/iou/thinapk/demo/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.hm.iou.thinapk.demo; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumented test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.hm.iou.thinapk.demo", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /app/src/main/java/com/hm/iou/thinapk/demo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.hm.iou.thinapk.demo; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.view.View; 7 | import android.widget.Button; 8 | 9 | import com.hm.library1.LibTest1Activity; 10 | 11 | import butterknife.BindView; 12 | import butterknife.ButterKnife; 13 | import butterknife.OnClick; 14 | 15 | public class MainActivity extends AppCompatActivity { 16 | 17 | @BindView(R2.id.btn_start) 18 | Button mBtnStart; 19 | 20 | @Override 21 | protected void onCreate(Bundle savedInstanceState) { 22 | super.onCreate(savedInstanceState); 23 | setContentView(R.layout.activity_main); 24 | ButterKnife.bind(this); 25 | } 26 | 27 | @OnClick(value = {R2.id.btn_start, R2.id.btn_close, R2.id.btn_send}) 28 | void onClick(View v) { 29 | if (v.getId() == R.id.btn_start) { 30 | startActivity(new Intent(this, LibTest1Activity.class)); 31 | int i = com.hm.library1.R.id.action0; 32 | } 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 |