使用 gradle extra properties管理dependencies的版本号
假设你的app-module的 build.gradle文件是这样的:
apply plugin: 'com.android.application'
android {
...
}
...
dependencies {
// support libraries
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:percent:23.4.0'
compile 'com.android.support:cardview-v7:23.4.0'
compile 'com.android.support:gridlayout-v7:23.4.0'
//play services
compile 'com.google.android.gms:play-services-location:9.2.1'
compile 'com.google.android.gms:play-services-gcm:9.2.1'
// other dependencies
...
}
可以看到包括支持库在内的几个版本号是重复的。为此我们可以使用gradle的extra属性来统一定义这些版本号。
在app模块的 build.gradle文件中增加一个ext块,并在里面定义变量,然后在dependencies中用定义好的变量替换固定的版本号。
apply plugin: 'com.android.application'
android {
...
}
...
ext {
supportLibraryVersion = '23.4.0'
playServicesVersion = '9.2.1'
}
dependencies {
// support libraries
compile "com.android.support:appcompat-v7:$supportLibraryVersion"
compile "com.android.support:design:$supportLibraryVersion"
compile "com.android.support:percent:$supportLibraryVersion"
compile "com.android.support:cardview-v7:$supportLibraryVersion"
compile "com.android.support:gridlayout-v7:$supportLibraryVersion"
//play services
compile "com.google.android.gms:play-services-location:$playServicesVersion"
compile "com.google.android.gms:play-services-gcm:$playServicesVersion"
// other dependencies
...
}
等等,先仔细看看区别何在:
compile 'com.android.support:appcompat-v7:23.4.0' 变成了:
compile "com.android.support:appcompat-v7:$supportLibraryVersion"
单引号变成了双引号。
光这样还是不够,很多大型项目都有好几个模块,每个模块都有可能反复引用相同版本的库,如果按照上面的方法,每个module的 build.gradle文件都要定义一次ext,还是很麻烦。
为此,可以把ext移到root project 的build.gradle 文件中。
root build.gradle
buildscript {
...
}
allprojects {
...
}
...
ext {
// sdk and tools
minSdkVersion = 14
targetSdkVersion = 23
compileSdkVersion = 23
buildToolsVersion = '23.0.2'
// dependencies versions
supportLibraryVersion = '23.4.0'
playServicesVersion = '9.2.1'
}
然后module一级的build.gradle文件就可以这样写:
apply plugin: 'com.android.application'
android {
...
}
...
dependencies {
// support libraries
compile "com.android.support:appcompat-v7:$rootProject.supportLibraryVersion"
compile "com.android.support:design:$rootProject.supportLibraryVersion"
compile "com.android.support:percent:$rootProject.supportLibraryVersion"
compile "com.android.support:cardview-v7:$rootProject.supportLibraryVersion"
compile "com.android.support:gridlayout-v7:$rootProject.supportLibraryVersion"
//play services
compile "com.google.android.gms:play-services-location:$rootProject.playServicesVersion"
compile "com.google.android.gms:play-services-gcm:$rootProject.playServicesVersion"
// other dependencies
...
}
拓展
其实还可以用这种方法管理minSdkVersion, targetSdkVersion, compileSdkVersion and buildToolsVersion 等
完整的例子见:gist。
来源:https://segunfamisa.com/posts/android-gradle-extra-properties