最近发现使用Android Studio编译项目,非常慢,每次编译运行需要2分钟。又遇版本上线,郁闷。早上google一下,找到了问题所在及解决方案,在我的项目上,修改好后编译时间减少到20秒左右,还能接受。
问题起因:项目因为引用了比较多的类库,所以使用了MultiDex解决64k问题。这就导致了每次编译耗时两分钟的原因。
解决方案:在主module的build.gradle中使用Flavor区分编译过程,在开发模式下设置minSdkVersion 21,这样可以避免MultiDex编译过慢的情况。
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'
}
defaultConfig {
applicationId "com.something.something"
targetSdkVersion 23
versionCode 1
versionName "1.0.0"
multiDexEnabled true
}
}
dependencies {
compile 'com.android.support:multidex:1.0.1'
}
在自己的Application中,添加:
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
最后,注意运行指定Build Variants为devDebug:
参考: