添加Fused Location Services时遇Dex方法数超限错误求助
解决「Cannot fit requested classes in a single dex file」错误(附Fused Location Services配置)
这个错误的核心原因很明确:你的项目里所有依赖的方法总数已经超过了Android单个Dex文件能容纳的65536个方法上限。看你的依赖配置,问题大概率出在com.google.android.gms:play-services:11.8.0——这个是Google Play服务的完整包,包含了地图、身份验证、位置服务等所有模块,方法数非常庞大,完全没必要全量引入。
下面给你两个递进的解决方案,优先尝试第一个:
1. 替换全量Play服务为单个位置服务模块
既然你只需要Fused Location Services,直接引入对应的独立模块即可,能大幅削减方法数:
- 把依赖里的
compile 'com.google.android.gms:play-services:11.8.0'替换成:
compile 'com.google.android.gms:play-services-location:11.8.0'
2. 开启MultiDex支持(如果替换模块后仍报错)
如果替换后方法数还是超限,就需要启用MultiDex,让App可以拆分多个Dex文件来容纳所有方法:
步骤1:添加MultiDex依赖
在dependencies块里新增:
compile 'com.android.support:multidex:1.0.3'
步骤2:启用MultiDex开关
在defaultConfig块里添加:
multiDexEnabled true
步骤3:配置Application类
- 如果你的项目有自定义Application类,让它继承
MultiDexApplication:
public class MyApplication extends MultiDexApplication { // 你的原有Application代码 }
- 如果无法修改Application的父类,就在
attachBaseContext方法里手动初始化MultiDex:
@Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); }
- 别忘了在
AndroidManifest.xml的application标签里指定你的自定义Application类(如果用了的话)。
修改后的完整build.gradle示例
apply plugin: 'com.android.application' android { compileSdkVersion 26 buildToolsVersion "27.0.1" defaultConfig { applicationId "com.example.adil.bloodbankapplication" minSdkVersion 15 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" // 启用MultiDex multiDexEnabled true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:appcompat-v7:26.1.0' compile 'com.android.support.constraint:constraint-layout:1.0.2' compile 'com.google.firebase:firebase-auth:11.8.0' compile 'com.google.firebase:firebase-database:11.8.0' compile 'com.android.support:support-v4:26.1.0' compile 'junit:junit:4.12' compile 'com.android.support:design:26.1.0' compile 'com.github.joielechong:countrycodepicker:2.1.5' compile 'com.jaredrummler:material-spinner:1.2.4' compile 'hanks.xyz:htextview-library:0.1.5' compile 'com.firebaseui:firebase-ui-database:1.2.0' // 替换为仅位置服务模块 compile 'com.google.android.gms:play-services-location:11.8.0' // 添加MultiDex依赖 compile 'com.android.support:multidex:1.0.3' } apply plugin: 'com.google.gms.google-services'
先尝试第一种方案,一般就能解决问题;如果还是不行,再开启MultiDex即可。
内容的提问来源于stack exchange,提问作者Muhammad Adil Sattar
相关产品推荐
相关产品推荐

