该文章同步更新到稀土掘金
升级AndroidStudio到Chipmunk版本后,可以发现创建项目时默认使用gradle-7.3.3版本。这时查看项目根目录的build.gradle文件可以发现有了变化:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '7.2.1' apply false
id 'com.android.library' version '7.2.1' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
再对比旧版本:
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:3.5.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
通过dependencies配置插件依赖的方式改成了plugins。
当然变化不止这一点,将一些通用配置移到了settings.gradle
pluginManagement {
repositories {
gradlePluginPortal()
google()
mavenCentral()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "GradlePluginDemo"
include ':app'
include ':libplugin'
这里以local repository的方式讲解
在旧版的配置中,我们只需要做三个事情:
// 这两步都在根目录的build.gradle的buildscript中配置
buildscript {
repositories {
// 1. 配置插件路径
maven {
url = uri('./local-plugin-repository')
}
}
dependencies {
// 2. 增加插件依赖
classpath 'com.king.libplugin:zipPNG:1.0'
}
}
// 在需要使用该插件的module的build.gradle引用插件
plugins {
id 'com.android.application'
// 3. 引用插件
id 'com.king.libplugin'
}
pluginManagement {
repositories {
gradlePluginPortal()
google()
mavenCentral()
// 1. 配置插件路径
maven {
url = uri('./local-plugin-repository')
}
}
resolutionStrategy {
eachPlugin {
println("resolutionStrategy eachPlugin ${requested.id.namespace}")
if (requested.id.namespace == 'com.king') {
// 2. 增加插件依赖
useModule("com.king.libplugin:zipPNG:${requested.version}")
}
}
}
}
// 这里跟旧版有点不同,需要配置version:因为在第一点中,会遍历子module的build.gradle的plugins中配置了以com.king开头的插件,然后使用useModule进行配置
plugins {
id 'com.android.application'
// 2. 引用插件
id 'com.king.libplugin' version '1.0'
}
void useModule(Object notation)
Sets the implementation module to use for this plugin.
Parameters:
notation - the module to use, supports the same notations as DependencyHandler
设置引用的plugin的具体实现模块
public class CustomPlugin implements Plugin {
@Override
public void apply(Project project) {
project.getTasks().register("zipPNG", new Action() {
@Override
public void execute(Task task) {
System.out.println("Hello from plugin 'com.example.plugin.customname'");
}
});
}
}
plugins {
// 用于配置自定义plugin
id 'java-gradle-plugin'
// 用于发布插件
id "maven-publish"
}
// 定义插件
gradlePlugin {
plugins {
zipPNG {
// 唯一,用于后续作为引用该插件的标识
id = 'com.king.libplugin'
// 指定插件的实现类
implementationClass = 'com.king.libplugin.CustomPlugin'
}
}
}
// 发布该插件
publishing {
publications {
mavenJava(MavenPublication) {
// 插件的组ID,建议设置为插件的包名
groupId = 'com.king.libplugin'
// 插件的名字,后续在引用时会用到
artifactId = 'zipPNG'
// 版本号
version = '1.0'
// 组件类型
from components.java
}
}
// 配置插件生成路径,这里为当前目录的local-plugin-repository目录下
repositories {
maven {
url uri('../local-plugin-repository')
}
}
}