1. 統一SDK版本管理配置
為了提高專案開發效率,在實際專案開發過程中往往會引入一些開源框架,還有專案中使用的各種Module,當引入Module過多時最好提供一種統一的方式去管理版本號,如:compileSdkVersion、buildToolsVersion、minSdkVersion等。
我在網上找了很多資料,網上提供了好幾種方案,寫法也有好幾種,不過最終原理其實都是差不多的,主要原理分為以下幾步:
一. 建立配置檔案config.gradle
配置資訊就放在這個檔案裡, 檔名字隨便取,字尾是.gradle即可。
情況一:檔案放在專案的 app目錄下,如下圖:appConfig.png

appConfig.png

config.png
二. 找到配置檔案config.gradle
情況一:檔案放在專案的 app目錄下
一般來說,放在 app目錄下config.gradle配置資訊,只能在主專案中引用,引用方式:
在app目錄下的build.gradle檔案開頭,加上apply from: 'config.gradle'。如下圖

a.png
情況二:檔案放在專案的 app目錄下
這種情況,config.gradle配置資訊可以全域性使用,在主工程和Module下都可以使用,統一SDK版本配置需要使用這種方式,引用方式:
在專案根目錄下的build.gradle檔案加上apply from: 'config.gradle'。如下圖

b.png
三. 引用配置資訊裡面的內容
1. config.gradle應該怎麼寫
網上有好幾種寫法,下面是我個人認為比較方便的方案
ext { //sdk版本管理 CompileSdkVersion = 26// 用於編譯的SDK版本 BuildToolsVersion = "28.0.3" // 用於Gradle編譯專案的工具版本 ApplicationId = "com.wanji.shop" //包名 MinSdkVersion = 19// 最低支援Android版本 TargetSdkVersion = 26// 目標版本 VersionCode = 1//版本號 VersionName = "1.0" MinifyEnabled = false //是否混淆 // App dependencies appcompatVersion = "26.1.0" constraintVersion = "1.1.3" junitVersion = "4.12" runnerVersion = "1.0.2" espressoVersion = "3.0.2" supportV4Version = "26.1.0" designVersion = "26.1.0" //公共的(系統的) roots = [ //專案基本的(每個專案需要的) "appcompatV7":"com.android.support:appcompat-v7:${appcompatVersion}", "constraint":"com.android.support.constraint:constraint-layout:${constraintVersion}", "junit":"junit:junit:${junitVersion}", "runner":"com.android.support.test:runner:${runnerVersion}", "espresso":"com.android.support.test.espresso:espresso-core:${espressoVersion}", ]
2. build.gradle怎麼引用
①:對於ext下的變數,網上的寫法:rootProject.ext.CompileSdkVersion或者ext.CompileSdkVersion,其實直接引用變數名CompileSdkVersion就可以了。
②:對於:roots陣列,直接roots.appcompatV7這樣引用就可以了。總體寫法如下:
apply plugin: 'com.android.application' android { compileSdkVersion CompileSdkVersion defaultConfig { applicationId ApplicationId minSdkVersion MinSdkVersion targetSdkVersion TargetSdkVersion versionCode VersionCode versionName VersionName testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled MinifyEnabled proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation roots.appcompatV7 implementation roots.constraint testImplementation roots.junit androidTestImplementation roots.runner androidTestImplementation roots.espresso }