当使用Android Studio创建一个项目后,会有三个和Gradle相关的文件,最外层目录下有一个build.gradle,app目录下也有一个build.gradle,最外层还有一个settings.gradle。
首先settings.gradle是说明该项目包含几个android应用。一般里面就一句话 include ‘:app’,单应用这个文件不是必须的。
最外层目录build.gradle中一般定义buildscript(构建时脚本)和allprojects(所有应用都包含脚本),注意buildscript中不能定义应用的依赖包。
应用下的build.gradle一般定义如下
#引入安卓插件
apply plugin: "com.android.application"
#引入上面插件后特有的配置
android {
#必有属性,用来编译应用的Android API版本
compileSdkVersion 28
#必有属性,构建工具和编译器使用的版本号
buildToolsVersion = 28.0.3
#应用的核心属性,用来替换AndroidManifest.xml中的相同属性
defaultConfig {
#应用的唯一标识用于设备和Google Play
applicationId "com.xxx"
#运行应用的最小Android API版本(rootProject.ext是顶层定义的额外属性)
minSdkVersion rootProject.ext.minSdkVersion
#不必启用任何先前兼容的Android API版本
targetSdkVersion 28
#版本号
versionCode 123
#版本名称
versionName "1.0"
}
#不同版本,一般不需要,是产品的一个分支,比如付费
productFlavors {
red {
applicationId "com.xxx.red"
versionCode 123
versionName "1.0"
}
}
#定义构建和打包不同类型的引用
buildTypes {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
#定义常量java中使用BuildConfig.API_URL
resValue("string","API_URL","http://test.example.com")
}
release {
debuggable false
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
#定义常量不同编译方式值不一样,像后台接口前缀
resValue("string","API_URL","http://example.com")
#启用ProGuard混淆并减小体积
minifyEnabled true
#缩减资源依赖库
shrinkResources true
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
}
#定义获取私钥任务
task getPassword << {
def password =''
if(rootProject.file(password.properties).exists()){
Properties properties = new Properties();
properties.load(rootProject.file(password.properties).newDataInputStream())
password = properties.getProperty('release.password')
}
if(!password?.trim()){
password = new String(System.console().readPassword("\n输入私钥"))
}
android.buildTypes.release.storePassword =password
android.buildTypes.release.keyPassword =password
}
#链接任务在packageRelease之前执行
tasks.whenTaskAdded{theTask ->
if(theTask.name.equals("packageRelease")){
theTask.dependsOn "getPassword"
}
}
#获取所有构建版本钩子
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
def file = output.outputFile
output.outputFile = new File(file.parent,file.name.replace(".apk","_${variant .versionName}.apk"))
}
}