Android MultiDex in details?

Manuchekhr Tursunov
2 min readFeb 24, 2023

--

MultiDex is a mechanism in Android that allows an app to use more than 65,536 method references. The Android platform uses Dalvik Executable (DEX) files to package application code. A DEX file contains compiled code that is executed by the Android runtime environment. The number of method references in a DEX file is limited to 65,536, so an app can only reference 65,536 methods.

If an app exceeds this limit, a build error occurs with the message “Cannot fit requested classes in a single dex file.” To solve this problem, the app must be configured to use MultiDex.

With MultiDex, an app can use more than one DEX file to hold its classes. The primary DEX file contains the classes that are used by the app at startup, while subsequent DEX files contain the classes that are loaded on demand.

To use MultiDex in an Android app, the following steps are typically required:

  1. Add the MultiDex library to the app’s dependencies.
  2. Enable MultiDex in the app’s build configuration.
  3. Update the app’s manifest file to include the MultiDex application class.
  4. Update the app’s proguard rules to prevent obfuscation of the MultiDex library classes.

Some examples of using MultiDex in Kotlin:

  • Enabling MultiDex in your Application class:
 class MyApplication : Application() {

override fun attachBaseContext(base: Context?) {
super.attachBaseContext(base)
MultiDex.install(this)
}

// rest of the code for your application class...
}
  • Implementing MultiDexApplication instead of Application:
class MyApplication : MultiDexApplication() {

// rest of the code for your application class...
}
  • Using MultiDex support in Gradle build file:
android {
defaultConfig {
//...
multiDexEnabled true
}
//...
}

dependencies {
implementation 'androidx.multidex:multidex:2.0.1'
}
  • Creating a custom Application class that extends MultiDexApplication:
class MyApplication : MultiDexApplication() {
// ...
}

Note: MultiDex is usually used when your app has more than 65,536 method references, which is the limit of the Dalvik Executable Format.

MultiDex can help an Android app overcome the method reference limit and support larger codebases.

--

--