Android uses Android-support-multidex to solve the problem of Dex exceeding the number of methods, so that your app is no longer bursting

Source: Internet
Author: User
Tags jcenter

if reproduced, please declare the source: Time of the Sand: http://blog.csdn.net/t12x3456 (from the sands of the CSDN blog)

as applications continue to iterate, lines of business expand, and applications become larger (such as the integration of various third-party SDKs or publicly supported JAR packages, project coupling is high, the number of repetitive classes is increasing), I believe many people have encountered the following errors:

Unexpected top-level EXCEPTION:java.lang.IllegalArgumentException:method ID not in [0, 0xFFFF]: 65536at Com.android.dx.merge.dexmerger$6.updateindex (dexmerger.java:501) at com.android.dx.merge.dexmerger$ Idmerger.mergesorted (dexmerger.java:282) at Com.android.dx.merge.DexMerger.mergeMethodIds (dexmerger.java:490) at Com.android.dx.merge.DexMerger.mergeDexes (dexmerger.java:167) at Com.android.dx.merge.DexMerger.merge ( dexmerger.java:188) at Com.android.dx.command.dexer.Main.mergeLibraryDexBuffers (main.java:439) at Com.android.dx.command.dexer.Main.runMonoDex (main.java:287) at Com.android.dx.command.dexer.Main.run (Main.java : @ com.android.dx.command.dexer.Main.main (main.java:199) at Com.android.dx.command.Main.main (main.java:103)

Yes, the number of Dex file methods in your app exceeds the maximum of 65536, so simply put, the app is bursting.

So let's see why this error is caused:

InAndroidSystem, aAppAll of the code is in aDexFile inside.Dexis a jar-like store that has manyJavaCompiles the archive file for the byte code. BecauseAndroidSystem useDalvikVirtual machines, so you need to useJava CompilerAfter compiling theclassConvert files intoDalvikCapable of performingclassFile. It is to be emphasized here thatDexAndJarSame as an archive file, which is stillJavaThe bytecode file that corresponds to the code. WhenAndroidWhen the system launches an application, one step is toDexTo be optimized, this process has a specialized tool to deal with, calleddexoptdexoptExecutes when the Dex file is loaded for the first time. This process generates aODEXfiles, i.e.Optimised Dex。 PerformODexwill be more efficient than direct execution.DexThe efficiency of the document is much higher. But in an earlier Android system,dexoptThere is a problem, which is what this article wants to illustrate and solve.dexoptWould put every method of a classIDRetrieved, there is a list structure inside. But the length of the list is with a ShortType to save, resulting in a methodIDCan not exceed the number of65536A. When a project is large enough, it is clear that the upper limit of this method is not enough. Although in the new version of theAndroidSystem,dexoptFixed this issue, but we still need to have a lower version of theAndroidSystem to be compatible.

At present, the more commonly used methods: (1) Application of plug-ins, such as the use of the plug-in framework I am participating in development: HTTPS://GITHUB.COM/SINGWHATIWANNA/DYNAMIC-LOAD-APK, if there are suggestions or related issues, welcome to active participation on Github. (2) Split Dex, multi-project: Compile a jar file with the required. class file or a jar file together with some source code. Then use the DX tool provided with the Android SDK to turn the jar file into a dex file. We can odex it before it is loaded by dexclassloader, skipping parts of dexopt and speeding up the loading process. These two methods do not conflict, plug-in In addition to solve the application bursting, there are many other advantages, you can see my previous article, no longer repeat.

Of course,Google seems to be aware of the current number of application methods of the problem, now in the API has provided a common solution, that is Android-support-multidex.jar . This jar package can support up to API 4 version ( Mutidexis supported by default onAndroid L and above).

Let's take a look at how to apply Android-support-multidex.jar (The following are examples of use in Anroid studio ):


The --multi-dex configuration (build.gradle) can be used first to resolve, the generated apk will contain more than one Dex file, such as Classes.dex, Classes2.dex. Build.gradle needs to be modified as follows:
afterevaluate {    tasks.matching {        it.name.startsWith (' dex ')    }.each {dx-and        if ( Dx.additionalparameters = = null) {            dx.additionalparameters = []        }        dx.additionalparameters + = '--multi-dex '//Enable Multidex        //optional        //Dx.additionalparameters + = "--main-dex-list= $projectDir/<filename>" . toString ()//enable the Main-dex-list    }}



But the default Dalvik ClassLoader will only look for classes.dex, so they need to be merged to make them recognized

Of course, now with the support of Android.support.multidex.jar, everything will become very simple, first of all, we look at the relevant source directory, the specific principles of analysis I will explain in the following article:
android/support/multidex/buildconfig.classandroid/support/multidex/multidex$v14.classandroid/support/multidex/ Multidex$v19.classandroid/support/multidex/multidex$v4.classandroid/support/multidex/multidex.classandroid/ support/multidex/multidexapplication.classandroid/support/multidex/multidexextractor$1.classandroid/support/ multidex/multidexextractor.classandroid/support/multidex/ziputil$centraldirectory.classandroid/support/ Multidex/ziputil.class

Specific integration:
Add the following configuration to the project ClassPathIn
repositories {  Jcenter ()}dependencies {  compile ' com.google.android:multidex:0.1 '}



The next integration has two steps:

I. Import Android-support-multidex.jar into the project from the Sdk\extras\android\support\multidex\library\libs directory

Two. If your project already contains the application class, then let it inherit the Android.support.multidex.MultiDexApplication class,

If your application has inherited other classes and does not want to make changes, there is another way to use it, overwrite the Attachbasecontext () method:



public class MyApplication extends Fooapplication {    @Override    protected void Attachbasecontext (Context base) { C5/>super.attachbasecontext (base);        Multidex.install (this);}    }


Finally, the complete configuration in Build.gradle is given:
Buildscript {    repositories {        jcenter ()    }    dependencies {        classpath ' com.android.tools.build: gradle:0.13.3 '        classpath ' jp.leafytree.gradle:gradle-android-scala-plugin:1.1 '    }}apply plugin: ' Com.android.application ' Apply plugin: ' Jp.leafytree.android-scala ' repositories {    jcenter ()}android {    Compilesdkversion    buildtoolsversion ' 21.0.2 '    defaultconfig {        applicationid ' Some.app '        Minsdkversion        targetsdkversion        versioncode 1        versionname ' 1.0 '    }}dependencies {    Compile ' com.google.android:multidex:0.1 '    compile ' com.android.support:support-v4:19.0.1 '    compile ' com.google.android.gms:play-services:5.0.77 '    compile ' org.scala-lang:scala-library:2.11.2 '    compile ' Org.scaloid:scaloid_2.11:3.4-10 '}



Things to do with Mutidex's ideas


If you inherit mutidexapplication or overwrite the Attachbasecontext () method in application.

Considerations for logic in the application class :

Static global variables in application are loaded more than the mutidex instal () method, so it is recommended that you avoid using them in the application class. the static variables that may be used in the main classes.dex file can be modified as follows:

@Override public    void OnCreate () {        super.oncreate ();        Final Context mcontext = this;        New Runnable () {            @Override public            void Run () {                //Put your logic here!                Use the Mcontext instead of this here            }        }.run ();    }


Problems


dexexception:library dex files is not supported in Multi-dex mode, you may see the following error:


Error:execution failed for task ': App:dexdebug ' .> com.android.ide.common.internal.LoggedErrorException:Failed to Run command:    $ANDROID _sdk/build-tools/android-4.4w/dx--dex--num-threads=4--multi-dex    ...  Error Code:    2  Output:    unexpected top-level EXCEPTION:    com.android.dex.DexException:Library Dex Files is not supported in Multi-dex mode at        Com.android.dx.command.dexer.Main.runMultiDex (main.java:322)        at Com.android.dx.command.dexer.Main.run (main.java:228) at        Com.android.dx.command.dexer.Main.main (Main.java : 199) at        Com.android.dx.command.Main.main (main.java:103)


the--multi-dex option setting for Dex is in conflict with the precompiled Library project, so if your app contains a referenced lirary project, you need to set the precompilation to false:
Android {    //...    dexoptions {        predexlibraries = False    }}



Outofmemoryerror:java Heap Space

When running, if you see the following error:
Unexpected top-level ERROR:java.lang.OutOfMemoryError:Java heap space

In dexoptionshas a field to increase the Java heap memory size:
Android {    //...    dexoptions {        javamaxheapsize "2g"    }}            


refer to the relevant information:

1. Mutidex Official document : https://developer.android.com/reference/android/support/multidex/MultiDex.html

2. http://blog.osom.info/2014/10/multi-dex-to-rescue-from-infamous-65536.html


Android uses Android-support-multidex to solve the problem of Dex exceeding the number of methods, so that your app is no longer bursting

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.