归根到底还是对AGP不熟悉~
AS新老工程AGP
AGP 全称为Android Gradle Plugin,安卓gradle插件,每个安卓工程都会使用这个插件。
1、老版本的工程中是这样用的
project#build.gradle文件 ->
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.7.21'
repositories {
google()
mavenCentral()
}
dependencies {
// 1、指定android gradle 插件 classpath
classpath 'com.android.tools.build:gradle:7.4.2'
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
app#build.gradle文件->
plugins {
//2、使用安卓gradle插件。
//这里标明app module是一个application 而不是一个android library.
id 'com.android.application'
id 'kotlin-android'
// 这样也可使用安卓gradle插件 id 'com.android.library',只是这样声明后代表module是一个android library
}
android {
...
}
dependencies {
...
}
2、新版本的工程中是这样用的
project#build.gradle文件 ->
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
// 指定agp,以及agp的版本。apply false 代表project不使用这个插件
// project要使用这个插件整个project也能run
id 'com.android.application' version '7.2.1' apply false
id 'com.android.library' version '7.2.1' apply false
id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
}
tasks.register('clean', Delete) {
delete rootProject.buildDir
}
app#build.gradle文件->
plugins {
// 2、apply agp
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id "com.contentsquare.error.analysis.network" version "1.1.0"
}
android {
...
}
dependencies {
...
}
3、一个三方插件引入的例子
Using legacy plugin application:
build.gradle
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2"
}
}
dependencies {
classpath "com.contentsquare.gradle:error-analysis-network:1.1.0"
}
}
app/build.gradle
apply plugin: "com.contentsquare.error.analysis.network"
Using the plugins DSL:
app/build.gradle
plugins {
id "com.contentsquare.error.analysis.network" version "1.1.0"
}
可见真的很简单,直接app/build.gradle中一行代码就搞定了。当然我们也可以这样做:
build.gradle
plugins {
id "com.contentsquare.error.analysis.network" version "1.1.0" apply false
}
app/build.gradle
plugins {
id "com.contentsquare.error.analysis.network"
}
注意一定不要在app/build.gradle中添加版本号否则会碰到一个Error ->
Error resolving plugin Plugin request for plugin already on the classpath must not include a version
小总结
- project build.gradle中buildscript必须放plugins之前
- gradle与 kts脚本语法也有区别
- 也可在app build.gradle中 通过 apply plugin 方式引入插件
目前碰到了这些小问题,其实要多多看下Android Gradle官方文档了解下AS AGP Gradle 几者存在版本关系