Gradle是一個(gè)基于Apache Ant和Apache Maven概念的項(xiàng)目自動(dòng)化構(gòu)建開(kāi)源工具仁热。它使用一種基于Groovy的特定領(lǐng)域語(yǔ)言(DSL)來(lái)聲明項(xiàng)目設(shè)置,拋棄了基于XML的各種繁瑣配置塌鸯。
1. 根目錄下的build.gradle
apply from: 'config.gradle' //應(yīng)用全局公共配置
buildscript {
// ext 用于定義動(dòng)態(tài)屬性
ext {
// 定義阿里云鏡像配置
repositories = [
'https://maven.aliyun.com/repository/central',
'https://maven.aliyun.com/repository/jcenter',
'https://maven.aliyun.com/repository/public',
'https://maven.aliyun.com/repository/google',
'https://maven.aliyun.com/repository/gradle-plugin',
'http://repo.springsource.org/libs-milestone-local'
]
}
// repositories閉包 配置遠(yuǎn)程倉(cāng)庫(kù)
repositories {
// 應(yīng)用阿里云鏡像配置
rootProject.ext.repositories.each { repourl ->
maven { url repourl }
}
google() // 代碼托管庫(kù):聲明后可引用google上的開(kāi)源項(xiàng)目
jcenter() // 代碼托管庫(kù):聲明后可引用jcenter上的開(kāi)源項(xiàng)目
}
// dependencies閉包 配置構(gòu)建工具
dependencies {
classpath 'com.android.tools.build:gradle:3.1.4' // 聲明gradle插件,插件版本號(hào)為3.1.4
//classpath "com.mob.sdk:MobSDK:2018.0319.1724"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath 'com.cpdroid:fat-aar:1.1.0'
}
// 增加一些編譯選項(xiàng)
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
}
}
allprojects {
repositories {
rootProject.ext.repositories.each { repourl ->
maven { url repourl }
}
google() // 代碼托管庫(kù):聲明后可引用google上的開(kāi)源項(xiàng)目
jcenter() // 代碼托管庫(kù):聲明后可引用jcenter上的開(kāi)源項(xiàng)目
}
}
// 運(yùn)行g(shù)radle clean時(shí)憾赁,執(zhí)行此處定義的task任務(wù)
// 該任務(wù)繼承自Delete娱颊,刪除根目錄中的build目錄
// 相當(dāng)于執(zhí)行Delete.delete(rootProject.buildDir)
task clean(type: Delete) {
delete rootProject.buildDir
}
// 打印引用的倉(cāng)庫(kù)地址
task printRepos {
doLast {
repositories.each { repourl ->
println "repository: ${repourl.name} ('${repourl.url}')"
}
}
}
2. module目錄下的build.gradle
// 聲明是Android程序
// com.android.application 表示這是一個(gè)應(yīng)用程序模塊, 可直接運(yùn)行
// com.android.library 標(biāo)識(shí)這是一個(gè)庫(kù)模塊, 作為代碼庫(kù)依附別的庫(kù)運(yùn)行
apply plugin: 'com.android.library'
def getProductName() { return "QuickUniSDK.Core" }
def config = rootProject.ext.android
// android閉包, 配置android構(gòu)建參數(shù)
android {
// 關(guān)閉Android Studio的PNG合法性檢查
aaptOptions.cruncherEnabled = false
aaptOptions.useNewCruncher = false
buildToolsVersion config.buildToolsVersion // build tools的版本, 其中包括了打包工具aapt、dx等等髓介。
compileSdkVersion config.compileSdkVersion // 編譯sdk的版本, 也就是API Level, 例如API-19惕鼓、API-20、API-21等等唐础。
// 默認(rèn)配置
defaultConfig {
minSdkVersion config.minSdkVersion // 最小sdk版本, 如果設(shè)備小于這個(gè)版本或者大于maxSdkVersion將無(wú)法安裝這個(gè)應(yīng)用
targetSdkVersion config.targetSdkVersion // 目標(biāo)sdk版本
versionCode config.versionCode // 版本號(hào)
versionName config.versionName // 版本名稱
archivesBaseName = "test-$versionName" // 指定打包成Jar文件時(shí)候的文件名稱
// 當(dāng)方法數(shù)超過(guò)65535(方法的索引使用的是一個(gè)short值箱歧,而short最大值是65535)的時(shí)候允許打包成多個(gè)dex文件,動(dòng)態(tài)加載dex
multiDexEnabled true
ndk {
moduleName "tttt" // 設(shè)置庫(kù)(so)文件名稱
ldLibs "log", "z", "m", "jnigraphics", "android"
//設(shè)置支持的SO庫(kù)架構(gòu)
//'armeabi-v7a', 'x86','armeabi'','x86_64','arm64-v8a'''
// 注:放開(kāi)'arm64-v8a'會(huì)找不到騰訊人臉識(shí)別的類庫(kù)包,>=android7.0 手機(jī)會(huì)崩潰
abiFilters 'armeabi-v7a', 'x86', 'arm64-v8a'
cFlags "-std=c++11 -fexceptions" // C++11
stl "gnustl_static"
}
// ARouter配置
javaCompileOptions {
annotationProcessorOptions {
arguments = [AROUTER_MODULE_NAME: project.getName()]
}
}
}
buildTypes {
// debug閉包指定生成測(cè)試版安裝文件的配置
debug {
buildConfigField('String', 'SERVER_ADDRESS', "xxxx") // 配置同字段不同開(kāi)發(fā)環(huán)境取不同的值
// manifest占位符
manifestPlaceholders = [
APP_NAME: "@string/app_name_xxxx",
]
zipAlignEnabled true // 是否對(duì)APK包執(zhí)行ZIP對(duì)齊優(yōu)化存捺,減小zip體積晋柱,增加運(yùn)行效率
shrinkResources true // 移除無(wú)用的resource文件
debuggable false // 是否支持調(diào)試
jniDebuggable false // 關(guān)閉jni調(diào)試
multiDexEnabled true // 是否啟動(dòng)自動(dòng)拆分多個(gè)dex的功能
multiDexKeepProguard file('multidex-config.pro')
minifyEnabled false // 是否開(kāi)啟混淆(上線)
// proguardFiles 指定混淆的規(guī)則文件
// proguard-android.txt 通用混淆規(guī)則
// proguard-rules.pro 自定義混淆規(guī)則
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release // 設(shè)置簽名信息
}
release.initWith(buildTypes.debug)
// release閉包指定生成正式版安裝文件的配置
release {
minifyEnabled false // 是否開(kāi)啟混淆(上線)
//shrinkResources true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8 // source使用的jdk版本
targetCompatibility JavaVersion.VERSION_1_8 // 編譯時(shí)使用的jdk版本或者更新的java虛擬機(jī)兼容
}
// DEX工具配置, multiDex的一些相關(guān)配置, 提升編譯速度
dexOptions {
preDexLibraries = false // 讓它不要對(duì)Lib做preDexing
incremental true // 開(kāi)啟incremental dexing缤苫,優(yōu)化編譯效率,這個(gè)功能android studio默認(rèn)是關(guān)閉的价淌。
javaMaxHeapSize "4g" // 增加java堆內(nèi)存大小
jumboMode = true
}
// 程序在編譯的時(shí)候會(huì)檢查lint, 有任何的錯(cuò)誤或者警告提示, 都會(huì)終止構(gòu)建, 我們可以將其關(guān)掉
lintOptions {
disable 'InvalidPackage'
abortOnError false // 即使報(bào)錯(cuò)也不會(huì)停止打包
checkReleaseBuilds false // 打包release版本的時(shí)候是否進(jìn)行檢測(cè)
quiet true // true 關(guān)閉lint報(bào)告的分析進(jìn)度
abortOnError false // true 錯(cuò)誤發(fā)生后停止gradle構(gòu)建
ignoreWarnings true // true 只報(bào)告error
//absolutePaths true // true 忽略有錯(cuò)誤的文件的全/絕對(duì)路徑(默認(rèn)是true)
checkAllWarnings true // true 檢查所有問(wèn)題點(diǎn),包含其他默認(rèn)關(guān)閉項(xiàng)
warningsAsErrors true // true 所有warning當(dāng)做error
disable 'TypographyFractions', 'TypographyQuotes' // 關(guān)閉指定問(wèn)題檢查
enable 'RtlHardcoded', 'RtlCompat', 'RtlEnabled' // 打開(kāi)指定問(wèn)題檢查
check 'NewApi', 'InlinedApi' // 僅檢查指定問(wèn)題
noLines true // true error輸出文件不包含源碼行號(hào)
showAll true // true 顯示錯(cuò)誤的所有發(fā)生位置瞒津,不截取
lintConfig file("default-lint.xml") // 回退lint設(shè)置(默認(rèn)規(guī)則)
textReport true // true 生成txt格式報(bào)告(默認(rèn)false)
textOutput 'stdout' // 重定向輸出, 可以是文件或'stdout'
xmlReport false // true 生成XML格式報(bào)告
xmlOutput file("lint-report.xml") // 指定xml報(bào)告文檔(默認(rèn)lint-results.xml)
htmlReport true // true 生成HTML報(bào)告(帶問(wèn)題解釋蝉衣,源碼位置,等)
htmlOutput file("lint-report.html") // html報(bào)告可選路徑(構(gòu)建器默認(rèn)是lint-results.html )
checkReleaseBuilds true // true 所有正式版構(gòu)建執(zhí)行規(guī)則生成崩潰的lint檢查巷蚪,如果有崩潰問(wèn)題將停止構(gòu)建
fatal 'NewApi', 'InlineApi' // 在發(fā)布版本編譯時(shí)檢查(即使不包含**重點(diǎn)內(nèi)容**lint目標(biāo))病毡,指定問(wèn)題的規(guī)則生成崩潰
error 'Wakelock', 'TextViewEdits' // 指定問(wèn)題的規(guī)則生成錯(cuò)誤
warning 'ResourceAsColor' // 指定問(wèn)題的規(guī)則生成警告
ignore 'TypographyQuotes' // 忽略指定問(wèn)題的規(guī)則(同關(guān)閉檢查)
}
// 打包配置
packagingOptions {
// pickFirsts作用是 當(dāng)有重復(fù)文件時(shí) 打包會(huì)報(bào)錯(cuò) 這樣配置會(huì)使用第一個(gè)匹配的文件打包進(jìn)入apk
// 表示當(dāng)apk中有重復(fù)的META-INF目錄下有重復(fù)的LICENSE文件時(shí) 只用第一個(gè) 這樣打包就不會(huì)報(bào)錯(cuò)
// pickFirsts = ['META-INF/LICENSE']
// merges作用 當(dāng)出現(xiàn)重復(fù)文件時(shí) 合并重復(fù)的文件 然后打包入apk
// 這個(gè)是有默認(rèn)值得 merges = [] 這樣會(huì)把默默認(rèn)值去掉 所以我們用下面這種方式 在默認(rèn)值后添加
// merge 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'org/bouncycastle/x509/CertPathReviewerMessages_de.properties'
exclude 'org/bouncycastle/x509/CertPathReviewerMessages.properties'
}
// 簽名配置
signingConfigs {
release { // release簽名配置
storeFile file("xxxx.keystore") // 密鑰文件路徑
storePassword "123456" // 密鑰文件密碼
keyAlias "xxxx" // key別名
keyPassword "123456" // key密碼
}
debug { // debug簽名配置
storeFile file("xxxx.keystore")
storePassword "123456"
keyAlias "xxxx"
keyPassword "123456"
}
}
// 配置目錄指向,默認(rèn)的一些文件路徑的配置
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml' // 指定AndroidManifest文件
java.srcDirs = ['src'] // 指定source目錄
resources.srcDirs = ['src'] // 指定source目錄
aidl.srcDirs = ['src'] // 指定source目錄
renderscript.srcDirs = ['src'] // 指定source目錄
res.srcDirs = ['res'] // 指定資源目錄
assets.srcDirs = ['assets'] // 指定assets目錄
jniLibs.srcDirs = ['libs'] // 指定lib庫(kù)目錄
}
debug.setRoot('build-types/debug') // 指定debug模式的路徑
release.setRoot('build-types/release') // 指定release模式的路徑
}
// 自動(dòng)追加版本號(hào)和版本名稱
android.libraryVariants.all { variant ->
variant.outputs.all { output ->
if (output.outputFile != null
&& output.outputFile.name.endsWith('.aar')
&& output.outputFile.size() != 0) {
def fileName = String.format("%s_v%s_%s_%s.aar", getProductName(), defaultConfig.versionName, rootProject.ext.common.packageTime, variant.buildType.name)
outputFileName = fileName
}
}
variant.assemble.doLast {
if (variant.buildType.name.contains('release')) {
def path = null
variant.outputs.each { output ->
path = output.outputFile
if (output.outputFile != null
&& output.outputFile.name.endsWith('.aar')
&& output.outputFile.size() != 0) {
copy { // 每次導(dǎo)出aar后 拷貝一份到指定目錄 作為備份 防止項(xiàng)目clean后找不到對(duì)應(yīng)版本的aar
from output.outputFile
into rootProject.ext.common.AARBackupDir
}
}
}
if (path != null) {
if (System.properties['os.name'].toLowerCase().contains('mac os x')) {
['open', '-R', path].execute()
} else if (System.properties['os.name'].toLowerCase().contains('windows')) {
['explorer', '/select,', path].execute()
}
}
}
}
}
}
tasks.withType(JavaCompile) {
// 在 Gradle 4.10 版本之后便默認(rèn)使用了增量編譯
// 如果在更老的版本需要啟動(dòng)增量編譯屁柏,可以使用如下配置:
options.incremental = true
// 解決java控制臺(tái)輸出中文亂碼
options.encoding = "UTF-8"
}
// 指定當(dāng)前項(xiàng)目的所有依賴關(guān)系 一共又三種依賴方式:本地依賴, 庫(kù)依賴, 遠(yuǎn)程依賴
// 本地依賴:可以對(duì)本地 Jar 包或目錄添加依賴關(guān)系
// 庫(kù)依賴:可以對(duì)項(xiàng)目中的庫(kù)模塊添加依賴關(guān)系
// 遠(yuǎn)程依賴:可以對(duì) jcenter 庫(kù)上的開(kāi)源項(xiàng)目添加依賴
// 標(biāo)準(zhǔn)的遠(yuǎn)程依賴格式是 域名:組織名:版本號(hào)
// implementation implementation依賴的庫(kù)只能自己庫(kù)本身訪問(wèn)
// api 使用該方式依賴的庫(kù)將會(huì)參與編譯和打包, 依賴傳遞
// compileOnly 只在編譯的時(shí)候有效, 不參與打包
// runtimeOnly 只在打包的時(shí)候有效, 編譯不參與
dependencies {
compileOnly files('libs/lib_unity/classes.jar')
//implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.0.0' // 遠(yuǎn)程依賴聲明
compileOnly fileTree(exclude: ['android-support*.jar'], include: ['*.jar'], dir: 'libs')
// 本地依賴聲明, 表示將libs目錄下所有.jar后綴的文件都添加到項(xiàng)目構(gòu)建路徑中
//implementation files('libs/soeasysdk_20181025.jar')
//implementation files('libs/libPluginProtocolForUnity_fat.jar')
}