Android Studio Gradle构建报错:Unable to merge dex 求助
解决Android Studio中DexArchiveMergerException:Unable to merge dex问题
既然你已经尝试开启multiDexEnabled true但问题仍存在,我来分享几个针对性的解决方案,帮你搞定这个dex合并错误:
1. 清理并重建项目
有时候构建缓存会导致各种奇怪的合并问题,先彻底清理再重建:
- 点击顶部菜单栏的 Build -> Clean Project
- 完成后再点击 Build -> Rebuild Project
2. 排查重复依赖冲突
你的dependencies里使用了fileTree引入libs目录下所有jar包,很可能存在本地jar和远程依赖重复的情况:
- 在Android Studio的Terminal中运行命令,生成完整依赖树:
仔细查看输出,寻找相同groupId和artifactId的重复依赖项。./gradlew app:dependencies - 如果发现重复,在对应的依赖中添加
exclude规则排除重复部分,比如:testImplementation 'junit:junit:4.12' { exclude group: 'org.hamcrest' }
3. 升级Gradle插件与Gradle版本
你的项目使用compileSdkVersion 26,对应的Gradle插件版本可能偏旧,尝试升级适配:
- 打开项目根目录的
build.gradle文件,更新classpath版本:buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.1' // 适配compileSdk 26的稳定版本 } } - 打开
gradle/wrapper/gradle-wrapper.properties,更新Gradle分发版本:distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
4. 验证assets目录与SQLite数据库文件
迁移项目时要确保assets目录配置正确:
- 确认数据库文件放在
app/src/main/assets目录下,右键该目录选择 Mark Directory as -> Assets Folder,让Android Studio正确识别它。 - 用SQLite工具打开数据库文件,验证文件是否损坏。
5. 关闭Instant Run功能
Instant Run有时会干扰构建流程,导致dex合并异常:
- 打开 File -> Settings -> Build, Execution, Deployment -> Instant Run
- 取消勾选 Enable Instant Run to hot swap code/resource changes on deploy,然后重启Android Studio。
额外排查步骤
如果以上方案都没解决,运行以下命令获取更详细的错误堆栈,定位具体冲突的库:
./gradlew app:transformDexArchiveWithExternalLibsDexMergerForDebug --stacktrace
从堆栈信息里你能看到到底是哪个库导致的合并失败,再针对性处理即可。
内容的提问来源于stack exchange,提问作者bcsta
相关产品推荐
相关产品推荐

