How to enable multidexing with the new Android Multidex support library
The following steps are needed to start multi dexing:
Add android-support-multidex.jar to your project. The jar can be found in your Android SDK folder /sdk/extras/android/support/multidex/library/libs
Now you either let your apps application class extend MultiDexApplication
public class MyApplication extends MultiDexApplication
or you override attachBaseContext like this:
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
I used the override approach because that does not mess with the class hierarchy of your application class.
Now your app is ready to use multi dex. The next step is to convince gradle to build a multi dexed apk. The build tools team is working on making this easier, but for the moment you need to add the following to the android part of your apps build.gradle
dexOptions {
preDexLibraries = false
}
And the following to the general part of your apps build.gradle
afterEvaluate {
tasks.matching {
it.name.startsWith('dex')
}.each { dx ->
if (dx.additionalParameters == null) {
dx.additionalParameters = ['--multi-dex']
} else {
dx.additionalParameters += '--multi-dex'
}
}
}
More info can be found on Alex Lipovs blog.
Edit:
Android 5.0 (API level 21) and higher uses ART which supports multidexing. Therefore, if your minSdkVersion
is 21 or higher, the multidex support library is not needed.
Modify your build.gradle
:
android {
compileSdkVersion 22
buildToolsVersion "23.0.0"
defaultConfig {
minSdkVersion 14 //lower than 14 doesn't support multidex
targetSdkVersion 22
// Enabling multidex support.
multiDexEnabled true
}
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
If you are running unit tests, you will want to include this in your Application
class:
public class YouApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
Or just make your application
class extend MultiDexApplication
public class Application extends MultiDexApplication {
}
For more info, this is a good guide.