新建Android项目构建失败:无法解析JUnit等依赖求助
Hey there! I remember hitting almost identical dependency snags when I built my first Android app—totally frustrating, but easy to fix once you spot the configuration kinks. Let's get your project up and running smoothly.
What's Causing the Problem?
Your errors boil down to two key issues:
- Incomplete repository configuration: Gradle can't locate JUnit and JSR305 because it's not looking in the right online repositories.
- Duplicate
androidblocks: Your app-level Gradle file has two separateandroid{}sections, which can confuse the build system and prevent settings from applying correctly.
Step 1: Fix the Project-Level build.gradle
Update your top-level build file to ensure Gradle can access all necessary libraries. Replace your allprojects block with this:
allprojects { repositories { google() // Official repo for AndroidX components jcenter() // Hosts JUnit and other third-party libraries mavenCentral() // Fallback repo for libraries migrating from jcenter } }
google() is the primary source for AndroidX dependencies, while jcenter() and mavenCentral() host the JUnit and JSR305 files your project needs.
Step 2: Clean Up the App-Level build.gradle
Merge the two separate android{} blocks in your app's Gradle file—this eliminates configuration conflicts. Here's the corrected version:
apply plugin: 'com.android.application' android { compileSdkVersion 29 buildToolsVersion "29.0.0" defaultConfig { applicationId "com.example.myapplication" minSdkVersion 28 targetSdkVersion 29 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } // Move resolution strategy into the single android block configurations.all { resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9' } } dependencies { implementation 'androidx.appcompat:appcompat:1.0.2' testImplementation 'junit:junit:4.12' }
Step 3: Final Troubleshooting Steps
- Click File > Sync Project with Gradle Files in Android Studio to apply your changes.
- If sync fails, go to File > Invalidate Caches... > Invalidate and Restart—this clears any cached bad configuration that might be sticking around.
- Double-check your internet connection: Gradle needs to download these dependencies, so make sure you're not blocked by a firewall or proxy.
Why This Works
- Consolidating the
androidblocks ensures Gradle reads all your configuration correctly without conflicts. - Adding the proper repositories tells Gradle exactly where to look for the missing JUnit and JSR305 libraries.
- The
resolutionStrategy.forceline ensures Gradle uses a JSR305 version that's fully compatible with your AndroidX setup.
You've got this—your first Android app is almost ready to run!
内容的提问来源于stack exchange,提问作者Aman

