Can I enable multidex in Android debug build only?

2019-02-16 08:53发布

问题:

Dears, I read in many blog posts that multidex apps startup is slower than normal apps. My app uses a lot of libraries that exceed 64k methods so I use multidex. But when I use proguard in release build, the final apk becomes less than 64k methods

So My question is: Can I enable multidex in Android debug build only so I don't have runtime error? and disable multi dex in release build as I don't need it?

If yes, how ?

If No, Is Android smart enough to speedup startup as it should recognize that app didn't exceed 64k even if it is multi dex app ?

回答1:

Yes, you can. When you declare your buildTypes include multidex only for debug:

buildTypes {
    release {
        multiDexEnabled false
    }
    debug {
        multiDexEnabled true
    }
}


回答2:

Instead of enabling multidex only for debug, you can change your min sdk version to 21 only for debug so gradle can speed up dexing with ART:

android {
    productFlavors {
        // Define separate dev and prod product flavors.
        dev {
            // dev utilizes minSDKVersion = 21 to allow the Android gradle plugin
            // to pre-dex each module and produce an APK that can be tested on
            // Android Lollipop without time consuming dex merging processes.
            minSdkVersion 21
        }
        prod {
            // The actual minSdkVersion for the application.
            minSdkVersion 14
        }
    }
          ...
    buildTypes {
        release {
            runProguard true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                                                 'proguard-rules.pro'
        }
    }
}
dependencies {
  compile 'com.android.support:multidex:1.0.0'
}

http://developer.android.com/tools/building/multidex.html



回答3:

suggested methods are not needed anymore as android studio became "smart enough". In fact, it will now give you a warning when you use minSdkVersion 21 (the old way) to speed up build time with dex:

You no longer need a dev mode to enable multi-dexing during development, and this can break API version checks less...

In the past, our documentation recommended creating a dev product flavor with has a minSdkVersion of 21, in order to enable multidexing to speed up builds significantly during development. That workaround is no longer necessary, and it has some serious downsides, such as breaking API access checking (since the true minSdkVersion is no longer known.) In recent versions of the IDE and the Gradle plugin, the IDE automatically passes the API level of the connected device used for deployment, and if that device is at least API 21, then multidexing is automatically turned on, meaning that you get the same speed benefits as the dev product flavor but without the downsides.