史上最全Android build.gradle配置详解,你懂的!
What is the difference between “sourceCompatibility” and “targetCompatibility”?
Android Studio系列之代码混淆proguardFiles
项目全局 build.gradle
TODO
模块中的 build.gradle
apply 部分
1 2
| apply plugin: 'com.android.application' apply plugin: 'com.android.library'
|
- 应用程序模块:可以直接运行,打包得到
.apk文件。
- 库模块:只能作为代码库依附别的应用程序模块运行,打包得到
.aar文件。
android { }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| android { compileSdkVersion 34 compileSdkVersion rootProject.ext.COMPILE_SDK_VERSION buildToolsVersion XX defaultConfig { applicationId "com.saoke.demo" minSdkVersion 16 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' buildConfigField 'int', 'VERSION_CODE', "${rootProject.ext.VERSION_CODE}" buildConfigField 'String', 'VERSION_NAME', "\"${rootProject.ext.VERSION_NAME}\"" } debug { } } }
|
Dependencies { }
定义依赖关系。
- 本地依赖:对本地的 jar 包或目录添加依赖关系
- 库依赖:对项目中的库模块添加依赖关系
- 远程依赖:对 Maven、jCener 上的项目添加依赖关系
1 2 3 4 5 6 7 8 9
| implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
implementation project(':moduleName')
implementation 'com.google.android.material:1.0.0' implementation("com.google.android.material:material:$DEV_VERSION.ANDROIDX_MATERIAL_VERSION")
|
implementation
用implementation引入的依赖参与编译和打包,且是不可传递的,只能在模块内部使用。如A模块依赖了Gson,则B模块无法访问Gson。
未使用的依赖不会被打包,因此可以减少编译时间和减少最终APK的大小。
api
与compile相同。
参与编译和打包。该依赖方式会传递所依赖的库,当其他模块依赖了该模块时,可以使用该模块下用 api 依赖的库。
compile
在 gradle 3.0 中已弃用,被implementation和api替代。
使用该方式依赖的库会参与编译和打包。
compileOnly
只在编译时有效,不会参与打包。通常用于开发阶段需要但最终打包时不需要的库,如在开发测试工具时,可能需要使用的一些测试相关的库。