AndroidStudio编译异常com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

今天遇到了传说中的“方法数超65536”的问题,贴出Gradle异常如下:

 
FAILURE: Build failed with an exception.
 
* What went wrong:
Execution failed for task ':ToddlerCare:transformClassesWithDexForInnertestJpushNochannelDebug'.
> com.android.build.api.transform.TransformException: 
  com.android.ide.common.process.ProcessException: 
  java.util.concurrent.ExecutionException: 
  com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
 
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
 
BUILD FAILED
 
Total time: 5 mins 28.887 secs

先贴出官方解决方案的链接:
http://developer.android.com/tools/building/multidex.html

再贴出stackoverflow问题链接:
http://stackoverflow.com/questions/27377080/after-update-of-as-to-1-0-getting-method-id-not-in-0-0xffff-65536-error-i

摘录解决步骤如下:
1、在build.gradle中,设置multiDexEnabled:

android {
   defaultConfig {
      multiDexEnabled true
   }
}

2、引入multidex库

dependencies {
   compile 'com.android.support:multidex:1.0.0'
}

3、将你的Aplication继承自MultiDexApplication,或是在manifest中指定application的属性

android:name="android.support.multidex.MultiDexApplication"

如果你的Application继承自别的类,那就需要重写attachBaseContext

protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}