
參考資料
Groovy
Gradle
- 書籍《Gradle in action》
- Gradle官方文檔
- Gradle中文文檔
- Groovy&Gradle總結(jié)
從移動應用到微服務,從小型創(chuàng)業(yè)公司到大企業(yè),Gradle幫助團隊更快地構(gòu)建,自動化并交付更好的軟件。
例子1:一個簡單的Gradle項目
本例子將創(chuàng)建一個簡單的Gradle項目,僅通過命令行調(diào)用一些基本的Gradle命令,主要目的是了解Gradle如何管理項目
準備環(huán)境
注:我的電腦系統(tǒng)是win10系統(tǒng),所以相關命令行用的是cmd
Java環(huán)境
java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)
gradle環(huán)境
------------------------------------------------------------
Gradle 4.4
------------------------------------------------------------
Build time: 2017-12-06 09:05:06 UTC
Revision: cf7821a6f79f8e2a598df21780e3ff7ce8db2b82
Groovy: 2.4.12
Ant: Apache Ant(TM) version 1.9.9 compiled on February 2 2017
JVM: 1.8.0_171 (Oracle Corporation 25.171-b11)
OS: Windows 10 10.0 amd64
初始化工程BasicDemo
新建BasicDemo文件,進入BasicDemo目錄
E:\Java>md BasicDemo
E:\Java>cd BasicDemo
E:\Java\BasicDemo>
執(zhí)行 init 任務(Task)
E:\Java\BasicDemo>gradle init
BUILD SUCCESSFUL in 1s
2 actionable tasks: 2 executed
任務執(zhí)行后,查看初始化后默認的工程結(jié)構(gòu)
E:\Java\BasicDemo>tree/F
卷 project 的文件夾 PATH 列表
卷序列號為 AF21-D274
E:.
│ build.gradle
│ gradlew
│ gradlew.bat
│ settings.gradle
│
├─.gradle
│ ├─4.4
│ │ ├─fileChanges
│ │ │ last-build.bin
│ │ │
│ │ ├─fileHashes
│ │ │ fileHashes.bin
│ │ │ fileHashes.lock
│ │ │
│ │ └─taskHistory
│ │ taskHistory.bin
│ │ taskHistory.lock
│ │
│ └─buildOutputCleanup
│ buildOutputCleanup.lock
│ cache.properties
│ outputFiles.bin
│
└─gradle
└─wrapper
gradle-wrapper.jar
gradle-wrapper.properties
簡單介紹下:
1.build.gradle:項目配置腳本,用于配置當前項目中的任務
2.gradle-wrapper.jar:Gradle Wrapper可執(zhí)行文件JAR
3.gradle-wrapper.properties:Gradle Wrapper配置屬性
4.gradlew:用于基于Unix的系統(tǒng)的Gradle Wrapper腳本
5.gradlew.bat:適用于Windows的Gradle Wrapper腳本
6.settings.gradle:用于配置哪些項目參與構(gòu)建的設置配置腳本
查看腳本
build.gradle
/*
* This build file was generated by the Gradle 'init' task.
*
* This generated file contains a commented-out sample Java project to get you started.
* For more details take a look at the Java Quickstart chapter in the Gradle
* user guide available at https://docs.gradle.org/4.4/userguide/tutorial_java_projects.html
*/
/*
// Apply the java plugin to add support for Java
apply plugin: 'java'
// In this section you declare where to find the dependencies of your project
repositories {
// Use 'jcenter' for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}
// In this section you declare the dependencies for your production and test code
dependencies {
// The production code uses the SLF4J logging API at compile time
compile 'org.slf4j:slf4j-api:1.7.25'
// Declare the dependency for your favourite test framework you want to use in your tests.
// TestNG is also supported by the Gradle Test task. Just change the
// testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
// 'test.useTestNG()' to your build script.
testCompile 'junit:junit:4.12'
}
*/
當前build.gradle沒有任何可執(zhí)行的腳本,只有一個應用java插件的模板腳本,腳本是被注釋了的
setting.gradle
/*
* This settings file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
* In a single project build this file can be empty or even removed.
*
* Detailed information about configuring a multi-project build in Gradle can be found
* in the user guide at https://docs.gradle.org/4.4/userguide/multi_project_builds.html
*/
/*
// To declare projects as part of a multi-project build use the 'include' method
include 'shared'
include 'api'
include 'services:webservice'
*/
rootProject.name = 'BasicDemo'
只有一句rootProject.name是設置項目名字的
查看默認的所有的Tasks
E:\Java\BasicDemo>gradlew tasks
Starting a Gradle Daemon (subsequent builds will be faster)
> Task :tasks
------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------
Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.
Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'BasicDemo'.
components - Displays the components produced by root project 'BasicDemo'. [incubating]
dependencies - Displays all dependencies declared in root project 'BasicDemo'.
dependencyInsight - Displays the insight into a specific dependency in root project 'BasicDemo'.
dependentComponents - Displays the dependent components of components in root project 'BasicDemo'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'BasicDemo'. [incubating]
projects - Displays the sub-projects of root project 'BasicDemo'.
properties - Displays the properties of root project 'BasicDemo'.
tasks - Displays the tasks runnable from root project 'BasicDemo'.
To see all tasks and more detail, run gradlew tasks --all
To see more detail about a task, run gradlew help --task <task>
BUILD SUCCESSFUL in 8s
1 actionable task: 1 executed
gradlew tasks相當于讓gradle執(zhí)行本項目的tasks任務,該任務會列出所有的task,有上面的內(nèi)容可以知道:
在Build Setup 任務組里面有init,wrapper兩個task,Help任務組里面有buildEnvironment,components等任務,每項任務后面有介紹。
所以這些任務是通用的,不管是什么項目都會有這些基本的Task
創(chuàng)建一個Task
Gradle提供了用于通過基于Groovy或Kotlin的DSL創(chuàng)建和配置任務的API。一個項目通常包括多個任務組,每個任務組里的每個任務都執(zhí)行一些基本操作。通過這些任務的組合,依賴構(gòu)成了一個項目的比如說編譯,打包,調(diào)式等過程,實際上IDEA那些按鈕最終執(zhí)行的也是這些任務
Gradle附帶一個可以在自己的項目中配置的任務庫,所以我們可以利用這些任務庫來定義自己想實現(xiàn)的任務
例子:復制文件,將src文件夾里的文件復制到dest文件夾中
步驟:
- 創(chuàng)建一個src文件夾
E:\Java\BasicDemo>md src
2.在src目錄下放一個文件,比如myfile.txt
E:\Java\BasicDemo>cd src
E:\Java\BasicDemo\src>type nul>myfile.txt
3.在build.gradle定義copy這個任務
task copy(type: Copy, group: "Custom", description: "Copies sources to the dest directory"){
from "src"
into "dest"
}
4.在看看現(xiàn)在該項目有沒有我定義的copy任務
E:\Java\BasicDemo>gradlew tasks
> Task :tasks
------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------
Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.
Custom tasks
------------
copy - Copies sources to the dest directory
Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'BasicDemo'.
components - Displays the components produced by root project 'BasicDemo'. [incubating]
dependencies - Displays all dependencies declared in root project 'BasicDemo'.
dependencyInsight - Displays the insight into a specific dependency in root project 'BasicDemo'.
dependentComponents - Displays the dependent components of components in root project 'BasicDemo'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'BasicDemo'. [incubating]
projects - Displays the sub-projects of root project 'BasicDemo'.
properties - Displays the properties of root project 'BasicDemo'.
tasks - Displays the tasks runnable from root project 'BasicDemo'.
To see all tasks and more detail, run gradlew tasks --all
To see more detail about a task, run gradlew help --task <task>
BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed
可以看到在Custom tasks已經(jīng)有copy這個任務了
5.最后執(zhí)行copy任務,看是不是真的有效果
E:\Java\BasicDemo>gradlew copy
BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed
E:\Java\BasicDemo>tree/F
卷 project 的文件夾 PATH 列表
卷序列號為 AF21-D274
E:.
│ build.gradle
│ gradlew
│ gradlew.bat
│ settings.gradle
│
├─.gradle
│ ├─4.4
│ │ ├─fileChanges
│ │ │ last-build.bin
│ │ │
│ │ ├─fileHashes
│ │ │ fileHashes.bin
│ │ │ fileHashes.lock
│ │ │
│ │ └─taskHistory
│ │ taskHistory.bin
│ │ taskHistory.lock
│ │
│ └─buildOutputCleanup
│ buildOutputCleanup.lock
│ cache.properties
│ outputFiles.bin
│
├─dest
│ myfile.txt
│
├─gradle
│ └─wrapper
│ gradle-wrapper.jar
│ gradle-wrapper.properties
│
└─src
myfile.txt
可以看到,src目錄下的文件已經(jīng)復制到dest文件夾里了,證明自定義的copy任務是可行的
應用一個Gradle插件
成千上萬的任務怎么管理,不可能都放在一起吧,所以gradle用插件來集成一些具有特定功能的任務集合,比如要構(gòu)建Android應用程序就要用com.android.application這個插件,構(gòu)建java應用要用java這個插件,目前gradle里面已經(jīng)有很多現(xiàn)成的插件了,可以https://plugins.gradle.org了解一下。其實很多開源框架附帶有配套的gradle插件,你要是覺得不夠自定義,自己也可以造一個
應用base插件
base插件里有一個Zip核心類型,我們可以用它來做一些文件壓縮操作
1.在builde.gradle添加應用插件的腳本
...
plugins {
id "base"
}
...
2.定義zip任務,將src文件壓縮為basic-demo-1.0.zip
task zip(type: Zip, group: "Archive", description: "Archives sources in a zip file") {
from "src"
setArchiveName "basic-demo-1.0.zip"
}
3.執(zhí)行zip任務
E:\Java\BasicDemo>gradlew zip
BUILD SUCCESSFUL in 1s
1 actionable task: 1 up-to-date
E:\Java\BasicDemo>tree/F
卷 project 的文件夾 PATH 列表
卷序列號為 AF21-D274
E:.
│ build.gradle
│ gradlew
│ gradlew.bat
│ settings.gradle
│
├─.gradle
│ ├─4.4
│ │ ├─fileChanges
│ │ │ last-build.bin
│ │ │
│ │ ├─fileHashes
│ │ │ fileHashes.bin
│ │ │ fileHashes.lock
│ │ │
│ │ └─taskHistory
│ │ taskHistory.bin
│ │ taskHistory.lock
│ │
│ └─buildOutputCleanup
│ buildOutputCleanup.lock
│ cache.properties
│ outputFiles.bin
│
├─build
│ └─distributions
│ basic-demo-1.0.zip
│
├─dest
│ myfile.txt
│
├─gradle
│ └─wrapper
│ gradle-wrapper.jar
│ gradle-wrapper.properties
│
└─src
myfile.txt
可以看到build/distributions目錄下有basic-demo-1.0.zip這個壓縮文件,證明插件應用成功
探索和分析構(gòu)建
查看可用的Task
執(zhí)行gradlew tasks這句命令,可以查看當前項目可用的Task,包括基本插件添加的和你自己定義添加的
使用 build scan
Gradle還為您的構(gòu)建提供了一個豐富的,基于Web的視圖,稱為構(gòu)建掃描。
例子:在剛才的zip任務后面加上--scan
E:\Java\BasicDemo>gradlew zip --scan
BUILD SUCCESSFUL in 1s
1 actionable task: 1 up-to-date
Publishing a build scan to scans.gradle.com requires accepting the Terms of Service defined at https://scans.gradle.com/terms-of-service. Do you accept these terms? [yes, no]
yes
Gradle Cloud Services license agreement accepted.
Publishing build scan...
https://gradle.com/s/gfdgkrh3xihcu
然后進https://gradle.com/s/gfdgkrh3xihcu這個網(wǎng)址,填入你的郵箱,然后會發(fā)一封郵件給你,郵件里就有構(gòu)建分析鏈接,界面如下圖:

很有檔次,那些大廠,有自己成熟的自動化流程才用這個功能吧
例子2 構(gòu)建一個簡單的Java應用程序
1.初始化項目BasicJava
新建BasicJava文件夾,使用gradle init命令
2.build.gradle添加java和application插件
apply plugin: 'java'
apply plugin: 'application'
repositories {
jcenter()
}
//main函數(shù)所在路徑
mainClassName = 'com.newtrekwang.basicjava.App'
dependencies {
compile 'org.slf4j:slf4j-api:1.7.25'
testCompile 'junit:junit:4.12'
}
java插件里有很多與java程序相關的構(gòu)建任務;application插件有運行程序的任務;repositories設置依賴倉庫來源,常見的就是jcenter();dependencies設置程序依賴的第三方庫,構(gòu)建的時候會從依賴倉庫去下載,比如上面就依賴了slf4f和junit
3.執(zhí)行gradlew tasks,看看有哪些任務
E:\Java\BasicJava>gradlew tasks
> Task :tasks
------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------
Application tasks
-----------------
run - Runs this project as a JVM application
Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the main classes.
testClasses - Assembles test classes.
Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.
Distribution tasks
------------------
assembleDist - Assembles the main distributions
distTar - Bundles the project as a distribution.
distZip - Bundles the project as a distribution.
installDist - Installs the project as a distribution as-is.
Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the main source code.
Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'BasicJava'.
components - Displays the components produced by root project 'BasicJava'. [incubating]
dependencies - Displays all dependencies declared in root project 'BasicJava'.
dependencyInsight - Displays the insight into a specific dependency in root project 'BasicJava'.
dependentComponents - Displays the dependent components of components in root project 'BasicJava'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'BasicJava'. [incubating]
projects - Displays the sub-projects of root project 'BasicJava'.
properties - Displays the properties of root project 'BasicJava'.
tasks - Displays the tasks runnable from root project 'BasicJava'.
Verification tasks
------------------
check - Runs all checks.
test - Runs the unit tests.
Rules
-----
Pattern: clean<TaskName>: Cleans the output files of a task.
Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration.
Pattern: upload<ConfigurationName>: Assembles and uploads the artifacts belonging to a configuration.
To see all tasks and more detail, run gradlew tasks --all
To see more detail about a task, run gradlew help --task <task>
BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed
4.新建Java源碼包和編寫Java源碼
│
└─src
└─main
└─java
└─com
└─newtrekwang
└─basicjava
App.java
java插件默認以src/main/java目錄下作為源碼存放路徑,你也可以在build.gradle里設置源碼路徑
App.java
package com.newtrekwang.basicjava;
public class App{
public static void main(String[] args){
System.out.println("hello world");
}
}
記得在build.gradle里設置好入口函數(shù)的位置,我這里就是mainClassName = 'com.newtrekwang.basicjava.App'
5.執(zhí)行gradle run 運行Java程序
E:\Java\BasicJava>gradlew run
> Task :run
hello world
BUILD SUCCESSFUL in 1s
2 actionable tasks: 1 executed, 1 up-to-date
- 打包為可執(zhí)行的jar文件
在build.gradle里添加jar設置,java插件自帶jar任務,必須要配置manifest,否則打出來的jar包沒有入口函數(shù)不能執(zhí)行。
jar{
baseName = 'BasicJava'
version = '2.0'
manifest {
attributes 'Main-Class': 'com.newtrekwang.basicjava.App'
}
}
執(zhí)行gradlew jar ,然后就可以在build/libs目錄下看到生成的jar文件了

執(zhí)行jar文件
E:\Java\BasicJava\build\libs>java -jar BasicJava-2.0.jar
hello world
例子3 構(gòu)建Android應用程序(多模塊)
構(gòu)建Android應用程序主要是要用com.android.tools.build:gradle這個庫里的com.android.application插件
因為Android Studio在創(chuàng)建項目的時候已經(jīng)為我們生成了相關的文件夾和基本的腳本文件,所以我們直接用AS創(chuàng)建一個Android工程
比如我創(chuàng)建了個Test工程:

實際上這個目錄結(jié)構(gòu)與前面的BasicDemo很類似,可以看作就是在BasicDemo上擴展的,只不過用到的Gradle插件不同,所以文件夾結(jié)構(gòu)也就有所不同。
根目錄的build.gradle
因為Android項目一般是多模塊的,就是一個項目可以有多個應用模塊或者依賴模塊,所以根目錄的build.gradle里的內(nèi)容一般與多模塊的公共配置有關
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
包含buildscript和allproject兩個塊,還有個clean任務,buildscript配置腳本的來源和腳本類路徑,repositories設置腳本倉庫地址,dependencies設置依賴那個庫,比如這里用的是com.android.tools.build:gradle:3.1.2,因為子模塊要用application這個插件,不設置的話會獲取不到這個插件。allprojects設置整個工程和子模塊的依賴倉庫來源,常見的就是google()和jcenter()
gradle腳本大量用到了groovy的閉包語法,閉包可以當方法參數(shù),而且調(diào)用方法可以不用加點,不用加圓括號,不熟悉的同學可以先去練下groovy閉包
比如
allprojects {
repositories {
google()
jcenter()
}
}
實際上是執(zhí)行了project對象的allprojects方法,傳入了
{
repositories {
google()
jcenter()
}
}
這個閉包,然后閉包里又調(diào)用了project對象的repositories方法,傳入了
{
google()
jcenter()
}
這個閉包,然后這個閉包里調(diào)用了RepositoryHandler對象的google()和jcenter()這兩個方法(閉包是可以改代理的,所以repositories方法的實現(xiàn)肯定是改了閉包的代理的,因為默認的project對象沒有google(),jcenter()這兩個方法)
根目錄的setting.gradle
include ':app'
配置項目包含哪些模塊,比如這里有個app模塊,那就把app這個文件夾添加上去
app目錄下的build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.newtrekwang.test"
minSdkVersion 18
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
首先應用了com.android.application這個插件,然后在相應的android,dependencies方法中通過閉包設置各種配置,依賴,具體指的是啥,這里暫時不展開敘述。
用AS查看Task

AS有個gradle工具窗口,從中可以查看所有的任務,這里是兩個分組,一個總工程Test的,一個app模塊的,再展開就能看到具體的task了,并且點擊可以執(zhí)行任務
例子4 模仿Android插件,定義一個簡單的gradle插件
模仿結(jié)果:定義一個com.newtrekwang.application插件,可以配置類似如下的腳本,然后腳本運行后打印出所有的配置信息。主要目的是了解Android插件的執(zhí)行流程,為什么可以這樣配置
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.newtrekwang.test"
minSdkVersion 18
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
1.為了快速構(gòu)建,用IDEA新建一個gradle工程,build.gradle應用groovy和maven插件。
build.gradle
apply plugin: 'groovy'
apply plugin: 'maven'
group 'com.newtrekwang.androidtools'
version '1.0.0'
repositories {
mavenCentral()
}
dependencies {
compile gradleApi()
compile localGroovy()
}
uploadArchives {
repositories {
mavenDeployer {
//本地的Maven地址設置為D:\\ProgramData\\repository
repository(url: 'file:D:\\ProgramData\\repository')
}
}
}
setting.gradle
rootProject.name = 'androidtools'
工程目錄:

1.在/src/main/groovy里面編寫插件源碼,結(jié)構(gòu)類似Java工程
因為android塊里有defaultConfig塊和buildTypes塊,defaultConfig塊里都是字段,所以定義一個Config類,buildTypes塊里是數(shù)組,所以定義一個BuildType放單元素里的字段
Config.groovy
package com.newtrekwang.androidtools
class Config {
String applicationId
int minSdkVersion
int targetSdkVersion
int versionCode
String versionName
String testInstrumentationRunner
@Override
public String toString() {
return "Config{" +
"applicationId='" + applicationId + '\'' +
", minSdkVersion=" + minSdkVersion +
", targetSdkVersion=" + targetSdkVersion +
", versionCode=" + versionCode +
", versionName='" + versionName + '\'' +
", testInstrumentationRunner='" + testInstrumentationRunner + '\'' +
'}';
}
}
BuildType.groovy
class BuildType {
String name
Boolean minifyEnabled
String fileName1
String fileName2
def proguardFiles(fileName1,fileName2){
this.fileName1 = fileName1
this.fileName2 = fileName2
}
def minifyEnabled(minifyEnabled){
this.minifyEnabled = minifyEnabled
}
def getDefaultProguardFile(s){
return s
}
BuildType(name){
this.name = name
}
@Override
public String toString() {
return "BuildType{" +
"name='" + name + '\'' +
", minifyEnabled=" + minifyEnabled +
", fileName1='" + fileName1 + '\'' +
", fileName2='" + fileName2 + '\'' +
'}';
}
}
Androrid.groovy
package com.newtrekwang.androidtools
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.model.ObjectFactory
class Android {
Integer compileSdkVersion
NamedDomainObjectContainer<BuildType> buildTypes
Config config
// 使閉包能夠給compileSdkVersion賦值
def compileSdkVersion(compileSdkVersion) {
this.compileSdkVersion = compileSdkVersion
}
// 嵌套集合對象容器
Android(NamedDomainObjectContainer<BuildType> buildTypes) {
this.buildTypes = buildTypes
}
// 注入對象工廠
def setConfig(ObjectFactory objectFactory) {
config = objectFactory.newInstance(Config.class)
}
// 使閉包配置生效,給config設置配置值
def defaultConfig(Closure closure) {
closure.delegate = config
closure()
}
// 固定用法,使buildTypes閉包配置生效
def buildTypes(Closure closure) {
buildTypes.configure closure
}
@Override
public String toString() {
return "Android{" +
"compileSdkVersion=" + compileSdkVersion +
", buildTypes=" + buildTypes +
", config=" + config +
'}';
}
}
2.再resources/META-INF/gradle-plugins里面添加插件配置文件,我的插件名叫myapplication.所以文件名為myapplication.properties
implementation-class=com.newtrekwang.androidtools.MyAndroidPlugin
里面的內(nèi)容是設置插件類的位置的
3.執(zhí)行uploadArchives,打包插件為jar包并發(fā)布再指定路徑

4.驗證插件
為了區(qū)分開來,我新建了另一個項目TestPlugin,專門用來測試插件,目錄結(jié)構(gòu)如下

build.gradle
buildscript{
repositories{
mavenCentral()
maven {
// 插件jar所在倉庫位置
url 'file:D:\\ProgramData\\repository'
}
}
dependencies {
// 依賴路徑
classpath 'com.newtrekwang.androidtools:androidtools:1.0.0'
}
}
app/build.gradle
apply plugin :'myapplication'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.newtrekwang.test"
minSdkVersion 18
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile("proguard-android.txt"), 'proguard-rules.pro'
}
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile("proguard-android.txt"), 'proguard-rules.pro'
}
}
}
app里的build.gradle完全模仿Android插件的配置樣子,插件名改為我的myapplication
配置完畢,同步下工程,會發(fā)現(xiàn)有printConfig任務

最后執(zhí)行printConfig任務

可以看到控制臺打印了所有配置信息,驗證完畢,達到模仿效果