运行Android代码遇DexException:多dex文件定义冲突,求解决方案
解决Android DexException: Multiple dex files define Lcom/google/android/gms/internal/measurement/zzabn;
这个错误本质是重复引入了相同的Google Play Services组件类,通常是因为项目里的不同依赖库使用了不同版本的com.google.android.gms:play-services-measurement相关模块,导致Dex合并时冲突。下面是一步步的解决方法:
统一Google Play Services库版本
这是最常见的解决方案。在项目根目录的build.gradle中,通过resolutionStrategy强制所有依赖使用同一版本的gms库,避免版本不一致带来的重复类:allprojects { repositories { // 保持你原有的仓库配置(比如google()、mavenCentral()等) } configurations.all { resolutionStrategy { // 强制指定measurement-base的版本,替换成你项目中使用的最新兼容版本 force 'com.google.android.gms:play-services-measurement-base:17.6.0' // 如果还有其他gms相关冲突,可以继续添加force规则,比如: // force 'com.google.android.gms:play-services-base:17.6.0' } } }排查并排除重复依赖
先通过命令查看项目完整的依赖树,找出引入重复measurement模块的来源:# macOS/Linux ./gradlew app:dependencies # Windows gradlew.bat app:dependencies在输出中搜索
com.google.android.gms:play-services-measurement,找到哪些第三方依赖引入了不同版本的该模块。然后在app模块的build.gradle中,给对应的依赖添加排除规则:implementation('com.example:your-third-party-lib:1.0.0') { exclude group: 'com.google.android.gms', module: 'play-services-measurement' }启用MultiDex(辅助方案)
如果你的项目minSdkVersion低于21,且确实存在方法数超过65k的情况(虽然这个错误主要是重复类,但可能伴随方法数超限),可以开启MultiDex:- 在app模块的
build.gradle中配置:android { defaultConfig { // ... multiDexEnabled true } } dependencies { implementation 'com.android.support:multidex:1.0.3' } - 自定义Application类继承
MultiDexApplication,或者在attachBaseContext中调用:@Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); }
- 在app模块的
清理缓存并重建项目
最后执行清理命令,清除旧的构建缓存,再重新构建:# macOS/Linux ./gradlew clean build # Windows gradlew.bat clean build
内容的提问来源于stack exchange,提问作者Ram Chhabra
相关产品推荐
相关产品推荐

