본문 바로가기

문제 해결

Cannot fit requested classes in a single dex file. 해결 방법

문제 발생

Error:Cannot fit requested classes in a single dex file...

이 오류는, 앱 내에서 참조될 수 있는 메소드의 총 개수가 65,536(64K)개를 초과해서 발생하는 오류로, '64K 참조 제한' 이라고 합니다.

앱이 참조하는 라이브러리에서 메소드가 64K를 초과하면, 빌드 제한에 도달했음을 알리는, 위의 빌드 오류 메시지가 발생하게 되는 것입니다.

 

이러한 제한을 해결하기 위해서는, multidex 지원 라이브러리를 구성하여 해결할 수 있습니다.

문제 해결

minSdkVersion 21 이상인 경우

minSdkVersion이 21 이상인 경우에는 multidex가 기본적으로 사용 설정되므로 추가적인 작업이 필요하지 않습니다.   

minSdkVersion 21 미만인 경우

  • app/build.gradle 파일에 multiDexEnabled를 true로 설정
  • multidex 라이브러리 추가
  • Application 클래스를 재정의 하지 않은 경우, manifest파일의 <application/> 태그에 android:name 설정
  • Application 클래스를 재정의 한 경우, MultiDexApplication 을 확장하도록 변경 (또는 Multidex.install(this) 설정) 
android {
    ...
    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 29
        multiDexEnabled true  //multidex 사용 설정
        ...
    }
}

//multidex 라이브러리 추가
dependencies {
        // AndroidX를 사용하는 경우
        implementation 'androidx.multidex:multidex:2.0.1'       
        // AndroidX를 사용하지 않는 경우       
        implementation 'com.android.support:multidex:1.0.3'
}

Application 클래스를 재정의 하지 않은 경우, manifest 파일의 <application/> 태그에 아래와 같이 android:name를 설정합니다.

<?xml version="1.0" encoding="utf-8"?>
   
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
       
package="com.example.myapp">
       
<application
               
android:name="android.support.multidex.MultiDexApplication" >
            ...
       
</application>
   
</manifest>

Application 클래스를 재정의 한 경우, 아래와 같이 MultiDexApplication을 확장합니다 (가능한 경우)

 

class MyApplication : MultiDexApplication() {...}

 

Application 클래스를 재정의하지만, 기본 클래스를 변경할 수 없는 경우에는 attachBaseContext() 메소드를 재정의하고,

MultiDex.install(this) 을 호출하여 multidex 사용을 설정합니다.

 

class MyApplication : SomeOtherApplication() {
    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }
}

 

위와 같이, multidex 적용을 완료한 후에 다시 빌드를 하면 정상적으로 빌드되는 것을 확인하실 수 있습니다 ^^