People who have done relatively large projects all know that , When app When it's big enough , There will be 65535 This mistake , That is to say 64K, That is to say , One app In bag , The number of methods cannot exceed 65535 individual , If it exceeds, it will be divided into several dex package , Don't ask why ,android The limitation of . It can also be understood as Android One of the "Bug".

Eclipse Era , To solve this problem , It's really painful , But never mind. , Now there is Android Studio 了 , This problem is easy to solve , official It also gives a definite solution .

here , We should deal with it according to the situation , With Android5.0（Api：21） For the watershed .

5.0 We need to solve this problem in the future , It's very simple

 minSdkVersion 21
targetSdkVersion 21
multiDexEnabled true


As long as it is minSdkVersion yes 21（ Or more ） Of , It's right there build.gradle Add one more multiDexEnabled true , It's just minSdkVersion Just add it inside the braces .

however , For the moment , There are still many in China 4.X The system of , therefore , We have to take the following approach ：

android {
defaultConfig {
...
minSdkVersion 15
targetSdkVersion 26
multiDexEnabled true
}
...
}
dependencies {
compile 'com.android.support:multidex:1.0.1'
}


then , Write your own   Application class , And let it inherit from  MultiDexApplication

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
android:name="android.support.multidex.MultiDexApplication" >
...
</application>
</manifest>

public class MyApplication extends MultiDexApplication { ... }

If , This step , You can't achieve , in other words , Yours Application Has inherited other Application 了 , You can do that ：

public class MyApplication extends SomeOtherApplication {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(context);
Multidex.install(this);
}
}


It's that simple , It's done in two steps ,Android Studio It's convenience .

For further details, please refer to the official . This is the official text （ Or just click on the link above ）.

 The number of configuration methods exceeds 64K Application
With Android The continuous growth of the platform ,Android The size of the app is also increasing . When your application and its referenced library reach a specific size , You will encounter build errors , Indicates that your application has reached Android The limits of application architecture . Earlier versions of the build system reported this error as follows ：
Conversion to Dalvik format failed:
Unable to execute dex: method ID not in [0, 0xffff]: 65536
Newer versions of Android Build systems that display different errors , But it indicates the same problem ：
trouble writing output:
Too many field references: 131000; max is 65536.
You may try using --multi-dex option.
These error conditions will show the following number ：65,536. This number is very important , Because it represents a single Dalvik Executable (DEX) The total number of references that can be called by code within a bytecode file . This page describes how to use the Dalvik The executable file is subcontracted to the application configuration to overcome this limitation , Enable your application to build and read Dalvik Executable subcontracting DEX file .
Android application (APK) File contains Dalvik Executable (DEX) Executable bytecode file in the form of file , It contains compiled code to run your application .Dalvik Executable Specifications will be available in a single DEX The total number of methods that can be referenced in a file is limited to 65,536, These include Android Framework approach 、 Library methods and methods in your own code . In the field of computer science , Term thousand （ abbreviation K） Express 1024（ or 2^10）. because 65,536 be equal to 64 X 1024, So this limitation is also called “64K Reference limit ”.
Android 5.0 Previous version Dalvik Executable subcontracting support
Android 5.0（API Level 21） Previous versions of the platform used Dalvik Run time to execute application code . By default ,Dalvik Limit every application APK Only a single... Can be used classes.dex Bytecode file . To get around this limitation , You can use Dalvik Executable subcontracting support library , It will be your main application DEX Part of the document , And then manage the other DEX Access to the file and the code it contains .
notes ： If your project is configured for Dalvik Executable subcontracting uses minSdkVersion 20 Or earlier , And you deploy it to run Android 4.4（API Level 20） Or a lower version of the target device , be Android Studio It's going to stop Instant Run.
Android 5.0 And later Dalvik Executable subcontracting support
Android 5.0（API Level 21） And later versions use the name ART Runtime , The latter supports from APK File load multiple DEX file .ART Precompile at application installation time , scanning classesN.dex file , And compile them into a single .oat file , for Android Equipment execution . therefore , If your minSdkVersion by 21 Or higher , You don't need to Dalvik Executable subcontracting support library .
If you need to know something about Android 5.0 Runtime details , see also ART and Dalvik.
notes ： If you will apply minSdkVersion Set to 21 Or higher , Use Instant Run when ,Android Studio The app is automatically configured for Dalvik Executable subcontracting . because Instant Run Only for debugged applications , You still need to configure the release build for Dalvik Executable subcontracting , To avoid 64K Limit .
avoid 64K Limit
Before configuring your app to support 64K Or more method references , You should take measures to reduce the total number of references that application code calls , Include methods defined by your application code or included Libraries . The following strategies can help you avoid achieving DEX Reference limit ：
Check the direct and delivery dependencies of your application - Make sure that the benefits of using any large dependency Library in your application outweigh the disadvantages of adding a lot of code to your application . A common negative pattern is , Just to use a few practical methods, add a very large library to the application . Reducing your application code dependencies can often help you avoid dex Reference limit .
adopt ProGuard Remove unused code - Enable code compression for your build to run ProGuard. Enabling compression ensures that you deliver APK Does not contain unused code .
Using these techniques eliminates the need to enable Dalvik Executable subcontracting , At the same time, it will reduce APK The overall size of .
Configure your application for Dalvik Executable subcontracting
Set your application project to use Dalvik Executable subcontracting configuration requires the following modifications to your application project , Depending on the minimum amount of application support Android edition .
If your minSdkVersion Set to 21 Or higher , You just need to be at the module level build.gradle file multiDexEnabled Set to true, As is shown here ：
android {
defaultConfig {
...
minSdkVersion 21
targetSdkVersion 26
multiDexEnabled true
}
...
}
however , If your minSdkVersion Set to 20 Or lower , You must use it as follows Dalvik Executable subcontracting support library ：
Modify module level build.gradle File to enable Dalvik Executable subcontracting , And will Dalvik Executable subcontract library added as dependency , As is shown here ：
android {
defaultConfig {
...
minSdkVersion 15
targetSdkVersion 26
multiDexEnabled true
}
...
}
dependencies {
compile 'com.android.support:multidex:1.0.1'
}
Depending on whether to replace Application class , Do one of the following ：
If you don't have a replacement Application class , Please edit the manifest file , Set as follows <application> In the tag android:name：
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
android:name="android.support.multidex.MultiDexApplication" >
...
</application>
</manifest>
If you replace Application class , Change it as follows to extend MultiDexApplication（ If possible ）：
public class MyApplication extends MultiDexApplication { ... }
perhaps , If you replace Application class , But you can't change the base class , Can be replaced by attachBaseContext() Method and call MultiDex.install(this) To enable Dalvik Executable subcontracting ：
public class MyApplication extends SomeOtherApplication {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(context);
Multidex.install(this);
}
}
After building the application ,Android The build tool builds the main DEX file (classes.dex) And the auxiliary DEX file （classes2.dex and classes3.dex etc. ）. then , Building a system will take all DEX The files are packaged into your APK in .
Runtime ,Dalvik Executable subcontracting API Use a special class loader to search for all of the DEX file （ Not just in the Lord classes.dex Search for ）.
Dalvik Limitations of executable subcontracting support library
Dalvik Executable subcontracting support library has some known limitations , When you incorporate it into your application build configuration , You should pay attention to these limitations and conduct targeted testing ：
Install... In device data partition during startup DEX The process of filing is quite complicated , If it helps DEX Larger files , It may cause the application to be unresponsive (ANR) error . In this case , You should go through ProGuard Apply code compression to minimize DEX File size , And remove the unused part of the code .
Due to the existence Dalvik linearAlloc error （ problem 22586）, Use Dalvik Executable subcontracting applications may not be able to run on a platform version earlier than Android 4.0（API Level 14） Start on your device . If your goal API Level below 14, Be sure to test these versions of the platform , Because your application may have problems starting or loading specific classes . Code compression can reduce or even eliminate these potential problems .
Due to the existence Dalvik linearAlloc Limit （ problem 78035）, therefore , If you use Dalvik The application of executable file subcontract configuration makes a huge memory allocation request , It may crash during operation . Even though Android 4.0（API Level 14） Increased distribution limits , But in Android 5.0（API Level 21） Previous Android On the version , Applications are still likely to encounter this limitation .
Declarant DEX The required classes in the file
by Dalvik Executable subcontracting builds each DEX When you file , The build tool performs complex decision making to determine the main DEX The required classes in the file , So that the application can start successfully . If any classes needed during startup are not in the main DEX Provided in the document , Then your application will crash with errors java.lang.NoClassDefFoundError.
This should not happen to code that is accessed directly from the application code , Because the build tool recognizes these code paths , But maybe the visibility is low in the code path （ Such as using a library with complex dependencies ） When . for example , If the code uses a self checking mechanism or calls from native code Java Method , Then these classes may not be recognized as primary DEX Required items in file .
therefore , If you receive java.lang.NoClassDefFoundError, You must use... In the build type multiDexKeepFile or multiDexKeepProguard Properties declare them , It's mainly to manually specify these other classes DEX Required items in file . If the class is multiDexKeepFile or multiDexKeepProguard Match in file , Then the class is added to the main DEX file .
multiDexKeepFile attribute
You are in multiDexKeepFile The file specified in should contain one class per line , And adopt com/example/MyClass.class The format of . for example , You can create a multidex-config.txt The file of , As shown below ：
com/example/MyClass.class
com/example/MyOtherClass.class
then , You can declare the file for the build type as follows ：
android {
buildTypes {
release {
multiDexKeepFile file 'multidex-config.txt'
...
}
}
}
please remember ,Gradle Will read relative to build.gradle Path to file , So if multidex-config.txt And build.gradle The files are in the same directory , The above example will work .
multiDexKeepProguard attribute
multiDexKeepProguard Document use and management Proguard The same format , And support the whole Proguard grammar . If you need to know something about Proguard Format and syntax details , see also Proguard In the manual Keep Options section .
You are in multiDexKeepProguard The file specified in should be in any valid ProGuard The grammar contains -keep Options . for example ,-keep com.example.MyClass.class. You can create a multidex-config.pro The file of , As shown below ：
-keep class com.example.MyClass
-keep class com.example.MyClassToo
If you want to specify all the classes in the package , The documents will be as follows ：
-keep class com.example.** { *; } // All classes in the com.example package
then , You can declare the file for the build type as follows ：
android {
buildTypes {
release {
multiDexKeepProguard 'multidex-config.pro'
...
}
}
}
Optimize the development of Dalvik Executable subcontracting
Dalvik Executable subcontract configuration can significantly increase build processing time , Because building a system has to decide which classes must be included in the main DEX File and which classes can be included in the auxiliary DEX Complex decisions are made in documents . That means using Dalvik Incremental build of executable subcontracting usually takes longer , It may slow down your development progress .
In order to shorten the time-consuming Dalvik Executable subcontract output build time , Please use productFlavors（ One development customization and one release customization , With different minSdkVersion value ） Create two build variants .
For development customization , take minSdkVersion Set to 21. This setting will enable a program named pre-dexing The construction function of , This function is only applicable to Android 5.0（API Level 21） And later versions of ART Format generation is faster Dalvik Executable subcontract output . For release customization , take minSdkVersion Set to your actual minimum support level . This setting generates Dalvik Executable subcontracting APK Compatible with more devices , But it takes longer to build .
The following build configuration example shows how to use Gradle Set these customizations in the build file ：
android {
defaultConfig {
...
multiDexEnabled true
}
productFlavors {
dev {
// Enable pre-dexing to produce an APK that can be tested on
// Android 5.0+ without the time-consuming DEX build processes.
minSdkVersion 21
}
prod {
// The actual minSdkVersion for the production version.
minSdkVersion 14
}
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
compile 'com.android.support:multidex:1.0.1'
}
After you complete this configuration change , Can be used for incremental build applications devDebug variant , The latter set dev Product customization and debug Build the attributes of a type in one . This will create the enabled Dalvik Executable files are subcontracted and disabled proguard The debuggable application of （ because minifyEnabled The default is false）. These settings will apply to Gradle Of Android The plug-in does the following ：
perform pre-dexing： Build each application module and each dependency as a separate DEX file .
Each one DEX File joining APK, And make no changes （ Do not perform code compression ）.
most important of all , modular DEX Files do not perform merge operations , Therefore, it can be avoided to determine the main DEX The content of the file is calculated for a long time .
The advantage of these settings is , You can build rapidly and incrementally , Because there are only modified modules DEX Files will be recalculated and repackaged during subsequent builds . however , These are built APK Can only be used in Android 5.0 Test on equipment . however , Because it's a custom configuration , You've kept the minimum amount of API Level and ProGuard The ability of code compression to perform normal builds .
You can also build other variants , Include prodDebug Variant construction , This variant takes longer to build , But it can be used for testing other than development . In the configuration shown ,prodRelease The variant will be the final test and release version . To learn more about using build variants , See configuring build variants .
Tips ： Because you have different options for Dalvik Different build variants of executable subcontracting requirements , So you can also provide different manifest files for different variants （ such , Only for API Level 20 And lower versions of the manifest file will change <application> Tag name ）, Or create a different... For each variant Application Subclass （ such , Only for API Level 20 And lower versions of the manifest file will expand MultiDexApplication Class or call MultiDex.install(this)）.
test Dalvik Executable subcontract application
Write for Dalvik The executable file is used to subcontract the instrument test of application , No other configuration is required .AndroidJUnitRunner Direct support for Dalvik Executable subcontracting , If you use MultiDexApplication Or replace your custom Application Object attachBaseContext() Method , And call MultiDex.install(this) Enabled Dalvik Executable subcontracting .
perhaps , You can replace AndroidJUnitRunner Medium onCreate() Method ：
public void onCreate(Bundle arguments) {
MultiDex.install(getTargetContext());
super.onCreate(arguments);
...
}
notes ： Currently not supported Dalvik Executable subcontracting to create tests APK.


## Android_65535 More articles on problem solving

1. IE6、7 Next html There are white spaces between labels , Causes and solutions of occupying extra white space after rendering

Directly above : reason : The div The content is carried out in the background print operation , Output . If nothing is output , The browser will add a blank character to the blank area by default . stay IE6.7 Next , When the browser parses the rendering , You think that whitespace is also in place , By default, it has the word ...

2. About solving python Several effective techniques for online problems

I haven't been to blog Garden for a long time after work , Although not very busy , But I'm not as free as I was when I was a student . Go to blog park today , Found that a lot of articles are year-end summary , Think about whether you should sum it up , But not yet , I'll write it when I think about it . Today, I'll write about the technical dry goods I use after work , dispute ...

3. DBImport V3.7 Version release and software stability （ Automatic exit problem ） Solution sharing

DBImport V3.7 Introduce : 1: First map , Let's talk about the highlight function : The main upgrade function is : 1: increase (Truncate Table) Clear and insert function : Clear it and plug it in , It can ensure that the data of the two libraries are consistent , I like this function very much . ...

4. MVVM Frame from WPF Migration to UWP Problems encountered and solutions

MVVM Frame from WPF Migration to UWP Problems encountered and solutions 0x00 cause I'm learning these days UWP 了 , Before a WPF Experience , So the overall feeling is OK , Looked at some basic concepts and themes , Wrote a few test programs , I suddenly remember that some time ago in W ...

5. java The solution to Chinese garbled code （ One ）----- Know the character set

A long silence ( It's been more than three months ),LZ" Beside oneself (with excitement one's excited feelings " Start blogging ! java The Chinese problem in coding is a platitude , Every time I encounter Chinese code disorder LZ Or according to previous experience , Or it is baidu.c ...

6. XStream take java Object to xml when , Underscores in object fields “_”, After the conversion, it became a two-way solution

In a project the other day , Due to the naming of database fields Two of them : One is called " Market price " One is called " Store prices " For the sake of distinguishing , So they were named as market ...

7. Lazy loading session Unable to open no session or session was closed terms of settlement （ Perfect solution ）

Let's start with ,hibernate Delay loading characteristics of (lazy). The so-called delayed loading is to perform the data loading operation only when the data needs to be queried . because hibernate It supports entity objects , Foreign keys are associated with entity objects . Such as ...

8. Use JSONObject.fromObject when “There is a cycle in the hierarchy” abnormal Solutions for

In the use of JSONObject.fromObject When , appear “There is a cycle in the hierarchy” abnormal .   It means there's a dead cycle , That is to say Model There is a cyclic inclusion relationship between : ...

9. iPhone Anywehre Virtual location tips “ Background service not started , Please re install the app and use ” Solutions for

Problem description : iPhone Escaped from prison , After the Cydia Install in Anywhere Virtual positioning , But turn it on app Tips : Background service not started , Please re install the app and use . The program doesn't work properly ... resolvent : open Cydia- already installed , ...

## Random recommendation

1. flashftp Connecting virtual machines centos Solutions to reporting errors

flashftp Connecting virtual machines centos Report errors , In general, it might be because of the port (22) I don't have access to First in centos Check in and open up 22 port , perform :iptables -I INPUT -p tcp --dport ...

Snackbar Snackbar Provides an alternative between Toast and AlertDialog Between lightweight controls , It can easily provide message prompt and action feedback .Snackbar Use and Toast It's basically the same : Snack ...

ios Use -webkit-text-size-adjust Do not resize the font body{-webkit-text-size-adjust: 100%!important;} android Use the following code , ...

4. spider autohome (1)

Code: #!/usr/bin/python # -*- coding: UTF-8 -*- import re import urllib import time def getHtml(url) ...

5. FreeBSD Route details

Computers on the same LAN are directly connected , But computers on different networks are not directly connected , Only through a special computer - Router to complete the connection . Routers connect to multiple network interfaces , Each network interface is connected to a corresponding network , Has a ...

6. PHP And session Related example tutorial and classic code

7. spring mvc Submit arrays and other complex types

Use jquery Submit , such as monthIncome The value of is an array , stay Java In the use request.getParameterValues("monthIncome"); Can 't get value , This is the way to ...

8. review -css Control text font properties

css Control text font properties font-family: HTTP: , Such as ”serif“”sans-serif“ font-size: Size font-style: Font style , Such as “normal,italic( Italics ).o ...

9. latex The matrix representation of

\$ \begin{matrix} 1 & 0 & 0\\ 0 & 1 & 0\\ 0 & 0 & 1 \end{matrix}\quad \begin{ ...

10. Use .mongorc.js Remove which comparisons “ dangerous ” Of shell Auxiliary function

Switch to the user directory vi .mongorc.js var no = function(){ print("Not on my watch."); }; // Database deletion is prohibited db.dr ...