添加Google Firebase为何引发Dex错误?
解决添加Firebase Core后方法数超过64K的问题
我来帮你搞定这个头疼的方法数超限问题!首先得搞清楚为什么加firebase-core:11.8.0会触发报错,而单独加play-services-maps或play-services-location却没事——原因很简单:旧版本的Firebase Core(比如你用的11.8.0)会隐式依赖完整的Google Play Services套件,而maps、location是Google拆分后的轻量化模块,方法数少很多,所以不会触发64K限制。
下面是具体的解决方案,按优先级来:
1. 启用Multidex(最直接的临时解决办法)
Android默认限制单个DEX文件最多包含64K个方法,开启Multidex可以让App生成多个DEX文件来绕过这个限制,步骤如下:
- 在你的
build.gradle(Module级)的defaultConfig块里添加multiDexEnabled true:
android { compileSdkVersion 26 buildToolsVersion "26.0.2" defaultConfig { applicationId "se.workshop.collect" minSdkVersion 21 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true // 新增这一行开启Multidex multiDexEnabled true } }
- 然后添加Multidex依赖:
dependencies { // 其他依赖... implementation 'com.android.support:multidex:1.0.3' }
- 如果你的App有自定义
Application类:- 要么让它继承
MultiDexApplication:class MyApplication : MultiDexApplication() { // ...你的业务代码 } - 要么在
attachBaseContext方法里手动初始化Multidex:class MyApplication : Application() { override fun attachBaseContext(base: Context) { super.attachBaseContext(base) MultiDex.install(this) } }
- 要么让它继承
2. 优化依赖,剔除不必要的库
如果你不想启用Multidex,可以检查依赖树,把Firebase Core带进来的多余Play Services库排除掉。用Gradle命令查看依赖关系:
./gradlew app:dependencyInsight --dependency com.google.android.gms:play-services --configuration debugCompileClasspath
找到那些你不需要的Play Services模块,在Firebase Core的依赖里排除它们,比如:
implementation ('com.google.firebase:firebase-core:11.8.0') { exclude group: 'com.google.android.gms', module: 'play-services-ads' exclude group: 'com.google.android.gms', module: 'play-services-games' // 按需排除其他不需要的模块 }
3. 升级Firebase和Play Services版本(推荐长期方案)
你用的11.8.0是非常老旧的版本了,新版本的Firebase已经做了模块化拆分,不会再默认引入完整的Play Services套件。更推荐用Firebase BOM来统一管理所有Firebase库的版本,避免版本不一致的问题:
dependencies { // 引入Firebase BOM,自动统一所有Firebase库版本 implementation platform('com.google.firebase:firebase-bom:32.7.0') // 可替换为最新稳定版 // 只添加你需要的Firebase模块,无需写版本号 implementation 'com.google.firebase:firebase-core' // 如果需要其他Firebase服务,直接添加即可 // implementation 'com.google.firebase:firebase-analytics' }
升级后不仅能解决方法数问题,还能获得更好的性能和更多新功能。
内容的提问来源于stack exchange,提问作者Joel Broström
相关产品推荐
相关产品推荐

