如何为Android应用配置Gradle 4.6版本?插件配置失败求助
Hey there! Let's sort out this Android Gradle Plugin (AGP) compatibility issue you're facing with Gradle 4.6. The root problem is that the old guide you referenced uses Gradle 2.3, which pairs with an outdated AGP version—your newer Gradle 4.6 needs a matching, updated plugin version to work properly.
Step 1: Update the Project-Level build.gradle
First, tweak the root directory's build.gradle to use the correct AGP version and modern repository sources:
// Root project build.gradle buildscript { repositories { // Google repo is mandatory for newer AGP versions google() jcenter() // Optional, for legacy dependencies } dependencies { // Gradle 4.6 pairs perfectly with AGP 3.2.x (we'll use 3.2.1 as an example) classpath 'com.android.tools.build:gradle:3.2.1' } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }
Step 2: Adjust the Module-Level build.gradle
Next, make sure your app module's build.gradle (usually in app/) aligns with AGP 3.2.x requirements:
// App module build.gradle apply plugin: 'com.android.application' android { compileSdkVersion 28 // Recommended for AGP 3.2.x; you can use higher compatible versions buildToolsVersion "28.0.3" defaultConfig { applicationId "com.example.helloapp" minSdkVersion 15 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' 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' }
Step 3: Sync and Build
- Open your terminal, navigate to your project root, and run:
./gradlew clean build # Linux/macOS # OR gradlew clean build # Windows - If you still hit errors, check these quick fixes:
- Ensure you can access the Google repository. If network access is restricted, swap in a domestic mirror (like Alibaba's Maven repo) in the
repositoriesblocks. - Verify
buildToolsVersionmatches yourcompileSdkVersion(e.g., compileSdk 28 needs buildTools 28.x.x).
- Ensure you can access the Google repository. If network access is restricted, swap in a domestic mirror (like Alibaba's Maven repo) in the
Quick Version Match Cheat Sheet
For your Gradle 4.6 setup, stick to this rule:
- Gradle 4.6 → AGP 3.2.x (versions like 3.2.0, 3.2.1, 3.2.2 all work)
- Avoid AGP 3.3.x+—those require Gradle 4.10.1 or higher, which your 4.6 can't support.
Pro tip: Anytime you upgrade Gradle later, double-check the official version compatibility table to avoid similar headaches!
内容的提问来源于stack exchange,提问作者user8821501

