Android Studio添加模块后启动报错:Unable to merge dex
Hey there, let's tackle this dex merging issue you're facing after adding a new module to your Android project. I've run into this plenty of times, so here are the most common fixes that usually get things back on track:
排查重复依赖冲突
This is the #1 culprit. Your new module might be pulling in a library that's already present in your main app module—often with conflicting versions. To spot this, open Android Studio's Terminal and run:# Mac/Linux ./gradlew app:dependencies # Windows gradlew.bat app:dependenciesScan the output for duplicate libraries (like different versions of
support-v4orokhttp). Once found, you can either align the versions across modules, or exclude the duplicate from one side. For example:implementation('com.example:your-library:1.0.0') { exclude group: 'com.android.support', module: 'support-v4' }启用Multidex支持
If your project's total method count exceeds the 65536 DEX limit, this error will pop up. To fix it, first enable Multidex in yourapp/build.gradle:android { defaultConfig { ... multiDexEnabled true } } dependencies { implementation 'com.android.support:multidex:1.0.3' }Then update your Application class: either make it extend
MultiDexApplication, or add this override if you're using a custom Application:public class MyApp extends Application { @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } }Don't forget to reference this class in your
AndroidManifest.xml.清理缓存并重建项目
Sometimes stale build cache causes weird merging issues. Start withBuild > Clean Projectin Android Studio, followed byBuild > Rebuild Project. If that doesn't work, manually delete thebuildfolders from both your main app and the new module, then re-run the build.验证Gradle与插件版本兼容性
Mismatched Android Gradle Plugin and Gradle versions can break dex merging. Check your top-levelbuild.gradlefor the plugin version (e.g.,com.android.tools.build:gradle:3.1.0) and make sure it's paired with a compatible Gradle version (you can update this ingradle/wrapper/gradle-wrapper.propertiesvia thedistributionUrlline).统一minSdkVersion across modules
Your new module'sminSdkVersioncan't be higher than your main app's—this causes dependency merging conflicts. Double-check that all modules in your project have matching (or app-compatible)minSdkVersionvalues in theirbuild.gradlefiles.
内容的提问来源于stack exchange,提问作者Carlos Cardoso

