├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── styles.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
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── layout
│ │ │ │ └── activity_main.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── hm
│ │ │ └── iou
│ │ │ └── thinapk
│ │ │ └── demo
│ │ │ └── MainActivity.java
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── hm
│ │ │ └── iou
│ │ │ └── thinapk
│ │ │ └── demo
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── hm
│ │ └── iou
│ │ └── thinapk
│ │ └── demo
│ │ └── ExampleInstrumentedTest.java
├── build.gradle
└── proguard-rules.pro
├── plugin
├── .gitignore
├── src
│ └── main
│ │ ├── resources
│ │ └── META-INF
│ │ │ └── gradle-plugins
│ │ │ └── com.hm.plugin.thinapk.properties
│ │ └── groovy
│ │ └── com
│ │ └── hm
│ │ └── iou
│ │ └── thinapk
│ │ └── plugin
│ │ ├── ThinApkPlugin.groovy
│ │ ├── ThinApkRExtension.groovy
│ │ ├── ThinApkRTransform.groovy
│ │ └── RClassUtil.groovy
└── build.gradle
├── library1
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ └── strings.xml
│ │ │ └── layout
│ │ │ │ └── activity_library_test1.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── hm
│ │ │ └── library1
│ │ │ ├── LibTest1Activity.java
│ │ │ └── test
│ │ │ └── LibTest2Activity.java
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── hm
│ │ │ └── library1
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── hm
│ │ └── library1
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── gradlew
├── README.md
└── LICENSE
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/plugin/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library1/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':plugin', ':library1'
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | HM-ThinApk
3 |
4 |
--------------------------------------------------------------------------------
/library1/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | library1
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/houjinyun/Android-ThinApk/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/plugin/src/main/resources/META-INF/gradle-plugins/com.hm.plugin.thinapk.properties:
--------------------------------------------------------------------------------
1 | implementation-class=com.hm.iou.thinapk.plugin.ThinApkPlugin
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/houjinyun/Android-ThinApk/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/houjinyun/Android-ThinApk/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/houjinyun/Android-ThinApk/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/houjinyun/Android-ThinApk/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/houjinyun/Android-ThinApk/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/houjinyun/Android-ThinApk/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/houjinyun/Android-ThinApk/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/houjinyun/Android-ThinApk/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/houjinyun/Android-ThinApk/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/houjinyun/Android-ThinApk/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Nov 13 19:59:47 CST 2018
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/library1/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/plugin/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java-library'
2 | apply plugin: 'groovy'
3 |
4 | apply plugin: 'com.github.dcendents.android-maven'
5 | group='com.github.houjinyun'
6 |
7 | dependencies {
8 | implementation fileTree(dir: 'libs', include: ['*.jar'])
9 |
10 | compile gradleApi()
11 | compile localGroovy()
12 |
13 | compile 'com.android.tools.build:transform-api:1.5.0'
14 | compile 'com.android.tools.build:gradle:3.0.1'
15 |
16 |
17 | }
--------------------------------------------------------------------------------
/library1/src/test/java/com/hm/library1/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.hm.library1;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/hm/iou/thinapk/demo/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.hm.iou.thinapk.demo;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/library1/src/main/res/layout/activity_library_test1.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
12 |
13 |
--------------------------------------------------------------------------------
/plugin/src/main/groovy/com/hm/iou/thinapk/plugin/ThinApkPlugin.groovy:
--------------------------------------------------------------------------------
1 | package com.hm.iou.thinapk.plugin
2 |
3 | import com.android.build.gradle.AppExtension
4 | import org.gradle.api.Plugin
5 | import org.gradle.api.Project
6 |
7 | class ThinApkPlugin implements Plugin{
8 |
9 | @Override
10 | void apply(Project project) {
11 | def android = project.extensions.getByType(AppExtension)
12 |
13 | project.extensions.create("thinRConfig", ThinApkRExtension, project)
14 | android.registerTransform(new ThinApkRTransform(project))
15 | }
16 |
17 | }
--------------------------------------------------------------------------------
/library1/src/main/java/com/hm/library1/LibTest1Activity.java:
--------------------------------------------------------------------------------
1 | package com.hm.library1;
2 |
3 | import android.app.Activity;
4 | import android.os.Bundle;
5 | import android.support.annotation.Nullable;
6 | import android.widget.TextView;
7 |
8 | import butterknife.BindView;
9 | import butterknife.ButterKnife;
10 |
11 | /**
12 | * Created by hjy on 2019/1/7.
13 | */
14 |
15 | public class LibTest1Activity extends Activity {
16 |
17 | @BindView(R2.id.tv_library_test1)
18 | TextView mTvTest;
19 |
20 | @Override
21 | protected void onCreate(@Nullable Bundle savedInstanceState) {
22 | super.onCreate(savedInstanceState);
23 | setContentView(R.layout.activity_library_test1);
24 | ButterKnife.bind(this);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 | pluginDev=false
--------------------------------------------------------------------------------
/library1/src/main/java/com/hm/library1/test/LibTest2Activity.java:
--------------------------------------------------------------------------------
1 | package com.hm.library1.test;
2 |
3 | import android.app.Activity;
4 | import android.os.Bundle;
5 | import android.support.annotation.Nullable;
6 | import android.widget.TextView;
7 |
8 | import com.hm.library1.R;
9 | import com.hm.library1.R2;
10 |
11 | import butterknife.BindView;
12 | import butterknife.ButterKnife;
13 |
14 | /**
15 | * Created by hjy on 2019/1/7.
16 | */
17 |
18 | public class LibTest2Activity extends Activity {
19 |
20 | @BindView(R2.id.tv_library_test1)
21 | TextView mTvTest;
22 |
23 | @Override
24 | protected void onCreate(@Nullable Bundle savedInstanceState) {
25 | super.onCreate(savedInstanceState);
26 | setContentView(R.layout.activity_library_test1);
27 | ButterKnife.bind(this);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/library1/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 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/library1/src/androidTest/java/com/hm/library1/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.hm.library1;
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.library1.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/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/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/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
12 |
18 |
19 |
25 |
26 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/library1/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.jakewharton.butterknife'
3 |
4 | android {
5 | compileSdkVersion 26
6 |
7 | defaultConfig {
8 | minSdkVersion 19
9 | targetSdkVersion 26
10 | versionCode 1
11 | versionName "1.0"
12 |
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 |
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 |
24 | }
25 |
26 | dependencies {
27 | implementation fileTree(dir: 'libs', include: ['*.jar'])
28 |
29 | implementation 'com.android.support:appcompat-v7:26.1.0'
30 | testImplementation 'junit:junit:4.12'
31 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
32 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
33 |
34 | compile 'com.jakewharton:butterknife:8.4.0'
35 | annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
36 | }
37 |
--------------------------------------------------------------------------------
/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/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/plugin/src/main/groovy/com/hm/iou/thinapk/plugin/ThinApkRExtension.groovy:
--------------------------------------------------------------------------------
1 | package com.hm.iou.thinapk.plugin
2 |
3 | import org.gradle.api.Action
4 | import org.gradle.api.NamedDomainObjectContainer
5 | import org.gradle.api.Project
6 |
7 | import java.util.regex.Pattern
8 | /**
9 | * Created by hjy on 2019/1/8.
10 | */
11 |
12 | class ThinApkRExtension {
13 |
14 | NamedDomainObjectContainer keepInfo
15 |
16 | ThinApkRExtension(Project project) {
17 | keepInfo = project.container(KeepRInfo)
18 | }
19 |
20 | void keepInfo(Action> action) {
21 | action.execute(keepInfo)
22 | }
23 |
24 | /**
25 | * 该R文件是否要keep住
26 | *
27 | * @param className eg:com/hm/thinapk/demo/R$mipmap.class
28 | * @return
29 | */
30 | KeepRInfo shouldKeepRFile(String className) {
31 | KeepRInfo keep = null
32 | keepInfo.each { KeepRInfo keepRInfo ->
33 | if (className == (keepRInfo.getRClassStr() + ".class")) {
34 | keep = keepRInfo
35 | }
36 | }
37 | return keep
38 | }
39 |
40 |
41 | static class KeepRInfo {
42 | String name
43 | //需要keep的包名,例如:com.hm.iou.thinapk.demo
44 | String keepRPackageName
45 | //需要keep的类名,例如 mipmap、drawable
46 | String keepRClassName
47 | //需要keep的资源名
48 | List keepResName
49 | //需要keep的资源名正则表达式
50 | List keepResNameReg
51 |
52 | private String rClassStr
53 |
54 | KeepRInfo(String name) {
55 | this.name = name
56 | }
57 |
58 | boolean shouldKeep(String fieldName) {
59 | if (keepResName != null && !keepResName.isEmpty()) {
60 | for (String name : keepResName) {
61 | if (name == fieldName) {
62 | return true
63 | }
64 | }
65 | }
66 | if (keepResNameReg != null && !keepResNameReg.isEmpty()) {
67 | for (String reg : keepResNameReg) {
68 | if (reg == null || reg == "")
69 | continue
70 | if (isMatch(fieldName, reg)) {
71 | return true
72 | }
73 | }
74 | }
75 | return false
76 | }
77 |
78 | String getRClassStr() {
79 | if (rClassStr == null) {
80 | rClassStr = "${keepRPackageName.replace(".", "/")}/R\$${keepRClassName}"
81 | }
82 | return rClassStr
83 | }
84 |
85 | boolean isMatch(String name, String reg) {
86 | Pattern pattern = Pattern.compile(reg)
87 | pattern.matcher(name).matches()
88 | }
89 |
90 | void printInfo() {
91 | println "packageName = ${keepRPackageName}, className = ${keepRClassName}"
92 | if (keepResName != null) {
93 | for (String name : keepResName) {
94 | println "keep res name: ${name}"
95 | }
96 | }
97 | println "RClass = ${getRClassStr()}"
98 | }
99 | }
100 |
101 | }
102 |
--------------------------------------------------------------------------------
/plugin/src/main/groovy/com/hm/iou/thinapk/plugin/ThinApkRTransform.groovy:
--------------------------------------------------------------------------------
1 | package com.hm.iou.thinapk.plugin
2 |
3 | import com.android.build.api.transform.*
4 | import com.android.build.gradle.internal.pipeline.TransformManager
5 | import org.apache.commons.codec.digest.DigestUtils
6 | import org.apache.commons.io.FileUtils
7 | import org.gradle.api.Project
8 | /**
9 | * 对R文件进行瘦身
10 | */
11 | class ThinApkRTransform extends Transform {
12 |
13 | Project project
14 | ThinApkRExtension extension
15 |
16 | ThinApkRTransform(Project project) {
17 | this.project = project
18 | }
19 |
20 | @Override
21 | String getName() {
22 | return "ThinApkRTransform"
23 | }
24 |
25 | @Override
26 | Set getInputTypes() {
27 | return TransformManager.CONTENT_CLASS
28 | }
29 |
30 | @Override
31 | Set super QualifiedContent.Scope> getScopes() {
32 | return TransformManager.SCOPE_FULL_PROJECT
33 | }
34 |
35 | @Override
36 | boolean isIncremental() {
37 | return false
38 | }
39 |
40 | @Override
41 | void transform(Context context, Collection inputs, Collection referencedInputs, TransformOutputProvider outputProvider, boolean isIncremental) throws IOException, TransformException, InterruptedException {
42 | extension = project.extensions.getByName("thinRConfig")
43 |
44 | println "----------------------------------"
45 | println "------ThinApkRTransform start-----"
46 |
47 | //先删除原来的缓存文件
48 | outputProvider.deleteAll()
49 | RClassUtil.clear()
50 |
51 | //记录所有的jar包
52 | def jarList = []
53 |
54 | println "----第一次遍历,开始收集R类信息----"
55 | inputs.each { TransformInput input ->
56 | //第一次循环,只是为了收集 R.java 类信息
57 | input.directoryInputs.each { DirectoryInput directoryInput ->
58 | if (directoryInput.file.isDirectory()) {
59 | directoryInput.file.eachFileRecurse { File file ->
60 | if (file.isFile()) {
61 | //收集R.java类的信息
62 | RClassUtil.collectRInfo(file)
63 | }
64 | }
65 | } else {
66 | //收集R.java类的信息
67 | RClassUtil.collectRInfo(directoryInput.file)
68 | }
69 | }
70 |
71 | input.jarInputs.each { JarInput jarInput ->
72 | def jarName = jarInput.name
73 | def md5 = DigestUtils.md5Hex(jarInput.file.getAbsolutePath())
74 | if (jarName.endsWith(".jar")) {
75 | jarName = jarName.substring(0, jarName.length() - 4)
76 | }
77 | def dest = outputProvider.getContentLocation(jarName + md5, jarInput.contentTypes, jarInput.scopes, Format.JAR)
78 |
79 | def src = jarInput.file
80 | FileUtils.copyFile(src, dest)
81 |
82 | //所有的jar包
83 | if (src.path.contains("com.squareup")) {
84 | //TODO 有很多jar其实是不需要处理的
85 | } else {
86 | jarList.add(dest)
87 | }
88 | }
89 | }
90 | println "----R类信息收集完毕----"
91 |
92 | println "----开始删除替换所有引用R.class的地方----"
93 | inputs.each { TransformInput input ->
94 | input.directoryInputs.each { DirectoryInput directoryInput ->
95 | if (directoryInput.file.isDirectory()) {
96 | directoryInput.file.eachFileRecurse {File file ->
97 | if (file.isFile()) {
98 | RClassUtil.replaceAndDeleteRInfo(file, extension)
99 | }
100 | }
101 | } else {
102 | RClassUtil.replaceAndDeleteRInfo(directoryInput.file, extension)
103 | }
104 |
105 | def dest = outputProvider.getContentLocation(directoryInput.name, directoryInput.contentTypes, directoryInput.scopes, Format.DIRECTORY)
106 | FileUtils.copyDirectory(directoryInput.file, dest)
107 | }
108 | }
109 |
110 | //处理 jar 包里的 class
111 | for (File jarFile : jarList) {
112 | println "处理Jar包里的R信息:${jarFile.getAbsolutePath()}"
113 | RClassUtil.replaceAndDeleteRInfoFromJar(jarFile, extension)
114 | }
115 |
116 | println "------ThinApkRTransform end-------"
117 | println "----------------------------------"
118 | }
119 |
120 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### 1. 前言
2 |
3 | 记得早期刚开始做 Android 开发的时候,一个 Android 应用也就几兆的大小。到现在,一个 APP少说十几兆,大则好几十兆甚至上百兆。所以针对 apk 包的瘦身问题,摆在了所有开发者的面前。毕竟安装包越小,下载安装肯定也就更快,对 APP 的运营也是有帮助的。网上已经有很多关于这方面的文章了,但是很多都泛泛而谈,道理大家都懂,但是怎么实操确不清楚。所以,本人计划将实际项目中用到的方案写出来,剖析剖析原理,一是给自己做个总结,二是给有需要的人做个参考,共同交流进步。
4 |
5 | ### 2. R.java 文件结构
6 |
7 | 众所周知,R.java 是自动生成的,它包含了应用内所有资源的名称到数值的映射关系。先创建一个最简单的工程,看看 R.java 文件的内容:
8 |
9 | 
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 |
--------------------------------------------------------------------------------
/plugin/src/main/groovy/com/hm/iou/thinapk/plugin/RClassUtil.groovy:
--------------------------------------------------------------------------------
1 | package com.hm.iou.thinapk.plugin
2 |
3 | import org.objectweb.asm.*
4 |
5 | import java.util.jar.JarEntry
6 | import java.util.jar.JarFile
7 | import java.util.jar.JarOutputStream
8 | import java.util.zip.ZipEntry
9 | /**
10 | * 优化处理R文件
11 | */
12 | class RClassUtil {
13 |
14 | /**
15 | * 收集所有 R.class 及其内部类里的 int 常量字段信息
16 | * 存储的 key = class全路径类名 + 字段名,value = 该字段的常量值
17 | */
18 | static Map mRInfoMap = new HashMap<>()
19 |
20 | /**
21 | * 清理掉缓存的数据
22 | */
23 | static void clear() {
24 | mRInfoMap.clear()
25 | }
26 |
27 | /**
28 | * 收集R类相关信息,将所有 R.class 类里的 int 常量值缓存起来
29 | *
30 | * @param file class文件
31 | */
32 | static void collectRInfo(File file) {
33 | if (!isRClass(file.absolutePath)) {
34 | return
35 | }
36 | def fullClassName = getFullClassName(file.getAbsolutePath())
37 | println "需要收集的R类信息:fullClassName = ${fullClassName}"
38 | new FileInputStream(file).withStream { InputStream is ->
39 | ClassReader classReader = new ClassReader(is)
40 | ClassVisitor classVisitor = new ClassVisitor(Opcodes.ASM5) {
41 | @Override
42 | FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
43 | if (value instanceof Integer) {
44 | //遍历读取所有 R.class 里的 int 常量值,例如 com/hm/library1/R$mipmap.class 里的 ic_launcher 常量值,
45 | //存储时存为 "com/hm/library1/R$mipmapic_launcher" = ***
46 | mRInfoMap.put(fullClassName - ".class" + name, value)
47 | }
48 | return super.visitField(access, name, desc, signature, value)
49 | }
50 | }
51 | classReader.accept(classVisitor, 0)
52 | }
53 | }
54 |
55 | /**
56 | * 删除单个class文件里的 R 信息,主要处理逻辑如下:
57 | * 1. 如果是 R.class 的内部类,R$styleable.class除外,直接删除里面的 int 常量值,保留 keep 住的常量值;
58 | * 2. 如果是 R$styleable.class,则删除里面的 int 常量值,保留 int[] 常量值;
59 | * 3. 如果是非 R.class文件,则将里面所有对 R.class 引用 int 常量的地方,直接替换成 int 数值;
60 | *
61 | * @param classFile
62 | */
63 | static void replaceAndDeleteRInfo(File classFile, ThinApkRExtension extension) {
64 | def fullClassName = getFullClassName(classFile.getAbsolutePath())
65 | //如果是除了R&styleable.class的除外
66 | if (isRFileExceptStyleable(classFile.getAbsolutePath())) {
67 | ThinApkRExtension.KeepRInfo keepRInfo = extension.shouldKeepRFile(fullClassName)
68 | if (keepRInfo != null) {
69 | println "有字段需要keep的R文件:${classFile.getAbsolutePath()}"
70 |
71 | new FileInputStream(classFile).withStream { InputStream is ->
72 | ClassReader classReader = new ClassReader(is.bytes)
73 | ClassWriter classWriter = new ClassWriter(0)
74 | ClassVisitor classVisitor = new ClassVisitor(Opcodes.ASM5, classWriter) {
75 | @Override
76 | FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
77 | if (value instanceof Integer) {
78 | if (keepRInfo.shouldKeep(name)) {
79 | println "keep了字段: ${name}"
80 | return super.visitField(access, name, desc, signature, value)
81 | }
82 | //不需要 keep 的字段,直接删除该 int 常量值
83 | return null
84 | }
85 | return super.visitField(access, name, desc, signature, value)
86 | }
87 | }
88 | classReader.accept(classVisitor, 0)
89 |
90 | byte[] bytes = classWriter.toByteArray()
91 | def newClassFile = new File(classFile.getParentFile(), classFile.name + ".tmp")
92 | new FileOutputStream(newClassFile).withStream { OutputStream os ->
93 | os.write(bytes)
94 | }
95 |
96 | //重命名
97 | classFile.delete()
98 | newClassFile.renameTo(classFile)
99 | }
100 |
101 | } else {
102 | println "没有字段需要keep,直接删除该R文件:${fullClassName}"
103 | classFile.delete()
104 | }
105 | } else {
106 | if (isRClass(classFile.getAbsolutePath())) {
107 | //如果是 R$styleable.class 则删除里面的 static final int 类型的字段
108 | println "删除${fullClassName}里的 static final int 字段"
109 |
110 | new FileInputStream(classFile).withStream { InputStream is ->
111 | ClassReader classReader = new ClassReader(is.bytes)
112 | ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES)
113 | ClassVisitor classVisitor = new ClassVisitor(Opcodes.ASM5, classWriter) {
114 | @Override
115 | FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
116 | //只替换 static final int 字段
117 | if (value instanceof Integer) {
118 | return null
119 | }
120 | return super.visitField(access, name, desc, signature, value)
121 | }
122 | }
123 | classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES)
124 |
125 | byte[] bytes = classWriter.toByteArray()
126 | def newClassFile = new File(classFile.getParentFile(), classFile.name + ".tmp")
127 | new FileOutputStream(newClassFile).withStream { OutputStream os ->
128 | os.write(bytes)
129 | }
130 |
131 | //重命名
132 | classFile.delete()
133 | newClassFile.renameTo(classFile)
134 | }
135 | } else {
136 | //如果是普通的类信息,则将引用 R 类的地方替换成 int 值
137 | new FileInputStream(classFile).withStream { InputStream is ->
138 | byte[] bytes = replaceRInfo(is.bytes)
139 | def newClassFile = new File(classFile.getParentFile(), classFile.name + ".tmp")
140 | new FileOutputStream(newClassFile).withStream { OutputStream os ->
141 | os.write(bytes)
142 | }
143 |
144 | //重命名
145 | classFile.delete()
146 | newClassFile.renameTo(classFile)
147 | }
148 | }
149 | }
150 | }
151 |
152 | /**
153 | * 遍历 jar 文件里的所有 class,替换所有对 R.class 的直接引用
154 | *
155 | * @param srcJar jar文件
156 | * @param extension
157 | */
158 | static void replaceAndDeleteRInfoFromJar(File srcJar, ThinApkRExtension extension) {
159 | File newJar = new File(srcJar.getParentFile(), srcJar.name + ".tmp")
160 | JarFile jarFile = new JarFile(srcJar)
161 |
162 | new JarOutputStream(new FileOutputStream(newJar)).withStream { JarOutputStream jarOutputStream ->
163 | jarFile.entries().each { JarEntry entry ->
164 | jarFile.getInputStream(entry).withStream { InputStream inputStream ->
165 | ZipEntry zipEntry = new ZipEntry(entry.name)
166 | byte[] bytes = inputStream.bytes
167 | if (entry.name.endsWith(".class")) {
168 | bytes = replaceRInfo(bytes)
169 | }
170 | if (bytes != null) {
171 | jarOutputStream.putNextEntry(zipEntry)
172 | jarOutputStream.write(bytes)
173 | jarOutputStream.closeEntry()
174 | }
175 | }
176 | }
177 | }
178 |
179 | jarFile.close()
180 | srcJar.delete()
181 | newJar.renameTo(srcJar)
182 | }
183 |
184 | /**
185 | * 将所有对 R.class 有引用的代码,直接替换成 int 值,这样在其他类里就不会内联 R.class 了,
186 | * R.class 存不存在就不会影响编译运行了
187 | *
188 | * @param bytes
189 | * @return
190 | */
191 | private static byte[] replaceRInfo(byte[] bytes) {
192 | ClassReader classReader = new ClassReader(bytes)
193 | ClassWriter classWriter = new ClassWriter(0)
194 | ClassVisitor classVisitor = new ClassVisitor(Opcodes.ASM5, classWriter) {
195 |
196 | @Override
197 | MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
198 | def methodVisitor = super.visitMethod(access, name, desc, signature, exceptions)
199 | methodVisitor = new MethodVisitor(Opcodes.ASM5, methodVisitor) {
200 | @Override
201 | void visitFieldInsn(int opcode, String owner, String name1, String desc1) {
202 | String key = owner + name1
203 | Integer value = mRInfoMap.get(key)
204 | if (value != null) {
205 | println "替换对R.class的直接引用:${owner} - ${name1}"
206 | super.visitLdcInsn(value)
207 | } else {
208 | super.visitFieldInsn(opcode, owner, name1, desc1)
209 | }
210 | }
211 | }
212 | return methodVisitor
213 | }
214 | }
215 | classReader.accept(classVisitor, 0)
216 | return classWriter.toByteArray()
217 | }
218 |
219 | /**
220 | * 判断该 class 文件是否是 R.class 类,及其内部类如 R$id.class
221 | *
222 | * @param classFilePath class文件的全路径名,例如:~app/build/intermediates/classes/debug/com/hm/library1/R.class
223 | * @return 如果是R.class及其它内部类class则返回true,否则返回false
224 | */
225 | static boolean isRClass(String classFilePath) {
226 | classFilePath ==~ '''.*/R\\$.*\\.class|.*/R\\.class'''
227 | }
228 |
229 | /**
230 | * 判断该 class 文件是否是 R.class 类,及其内部类如 R$id.class,但是 R$styleable.class 类排除在外
231 | *
232 | * @param classFilePath
233 | * @return
234 | */
235 | static boolean isRFileExceptStyleable(String classFilePath) {
236 | classFilePath ==~ '''.*/R\\$(?!styleable).*?\\.class|.*/R\\.class'''
237 | }
238 |
239 | /**
240 | * 从形如 ~/HM-ThinApk/app/build/intermediates/classes/debug/com/hm/library1/R.class 的类路径中截取出 com/hm/library1/R.class
241 | * 根据Android Studio版本的不同,编译配置不同,路径也可能不同,例如:app/build/intermediates/javac/officialDebug/compileOfficialDebugJavaWithJavac/classes/android/arch/lifecycle/R.class
242 | * 不管是当前工程的代码,还是远程依赖的aar包,在打包编译时,都会在工程的 app/build/intermediates/classes 路径下生成一系列R.class文件,
243 | * 根据打包模式是 debug 还是 release来区分,从中可以截取出 R.class 的包名了。
244 | *
245 | * @param filePath class文件全路径
246 | * @return 返回类似 "com/hm/library1/R.class"、"com/hm/library1/R$mipmap.class",其实就是类的全路径class名
247 | */
248 | static String getFullClassName(String filePath) {
249 | println "${filePath}"
250 |
251 | String mode = "/debug/"
252 | int index = filePath.indexOf(mode)
253 | if (index == -1) {
254 | mode = "/release/"
255 | index = filePath.indexOf(mode)
256 | }
257 | if (index != -1) {
258 | return filePath.substring(index) - "${mode}"
259 | }
260 |
261 | index = filePath.indexOf("/classes")
262 | filePath = filePath.substring(index) - "/classes" - "/debug" - "/release"
263 | filePath = filePath.substring(1)
264 | println filePath
265 | return filePath
266 | }
267 |
268 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------