Detailed explanation of Android packet MultiDex principles

Source: Internet
Author: User

Detailed explanation of Android packet MultiDex principles
Background of MultiDex

When the Android system installs an application, one step is to optimize Dex. In this process, there is a dedicated tool for processing, called DexOpt. DexOpt is executed when Dex files are loaded for the first time. This process generates an ODEX file, Optimised Dex. Execution of ODex is much more efficient than direct execution of Dex files.

However, in the early Android system, DexOpt had a problem. DexOpt would retrieve the method IDs of each class and put them in a linked list structure. However, the length of the linked list is saved as a short type, so that the number of method IDs cannot exceed 65536. When a project is large enough, it is clear that the maximum number of methods is not enough. Although DexOpt fixes this issue in the new version of Android, we still need to be compatible with earlier versions of Android.

To solve the problem that the number of methods exceeds the limit, you need to split the dex file into two or more. Therefore, Google officially launched the multidex compatibility package, with AndroidStudio, an APK contains multiple dex functions.

Simple Principle of MultiDex

Take the APK file with two dex files as an example. The second dex file is classes2.dex.

After the Applicaion is instantiated, the compatibility package checks whether the system version supports multidex and classes2.dex need to be installed. To install classes2.dex, extract classes2.dex from the APK and copy it to the sandbox directory of the application. Use reflection to inject classes2.dex into the current classloader.

The following is an official document.

Https://developer.android.com/tools/building/multidex.html#about
The author translates the official documents as follows:

Build an App that exceeds K

With the development of Android devices, the size of apps will become larger and larger. When developing an App, we usually encounter the following error when compiling our project due to the reported size and Reference Library:

 Conversion to Dalvik format failed: Unable to execute dex: method ID not in [0, 0xffff]: 65536

Of course, some system devices may see the following log information, but the same problem is reported:

trouble writing output:Too many field references: 131000; max is 65536.You may try using --multi-dex option.

The two error conditions display a common number: 65536. This number indicates that the number of Function Methods in a dex package exceeds 65535.

If you have built an Android App and received this error, congratulations! You have a lot of code!

Next, let's talk about how to solve this problem.

Limit on the 65K Method

We know that executable weijian in Android is stored in dex files and contains compiled code to run your application. The Dalvik virtual machine has method limitations on the specifications of executable dex files, that is, the total number of methods for a single dex file is up to 65536.

Including:

The reference Android Framework method library is a method for writing code by ourselves.

To break through the limit on the number of methods, we have proposed a solution to generate multiple dex files. This multi-dex file scheme is also called multidex scheme configuration.

Multidex supports versions earlier than Android 5.0
Before Android, Android used the program code executed by Dalvik Runtime. By default, the application is limited to a single classes. dex.

Dalvik bytecode file per APK. To bypass this restriction, you can use the multidex support library to become the main part of your application and manage DEX files to obtain additional dex files and the code they contain.

Multidex supports Android 5.0 and later versions.
Android 5.0 and higher Runtime, such as art, support loading multiple DEX files from the application's APK file. Art supports pre-compiled applications to scan classes during installation (..). The Dex file is compiled into a single Android device to execute the. oat file.

Avoid limit of 65K

When you are sure to use the multidex subcontracting policy, please first determine that your code is excellent. You also need to perform the following steps:

Remove unused import and library use ProGuard to Remove unused code Use Gradle to configure Multidex

Android's Gradle plug-in supports multidex since Android Build Tool 21.1.

Set your application development project to use the multidex configuration, requiring you to make some modifications to your application development project. :

Modify the configuration of Gradle and support multidex to modify your manifest. Make it support the multidexapplication class

Modify the Gradle build as follows:

android {    compileSdkVersion 21    buildToolsVersion "21.1.0"    defaultConfig {        ...        minSdkVersion 14        targetSdkVersion 21        ...        // Enabling multidex support.        multiDexEnabled true    }    ...}dependencies {  compile 'com.android.support:multidex:1.0.0'}

Tips: You can use multiDexEnabled in the Gradle configuration file in defaultConfig,
Set buildType and productFlavor options.

In the manifest file, add a MultidexApplication Class reference, as shown below:


  
  
               ...    
  

Of course, if you overwrite the Application, you can modify the Inheritance Method of the custom Application.

Limitations of Multidex

Although multidex is an excellent feature, multidex still has its own limitations. Before developing and testing, we need to know what the limitations are:

If the size of the DEX file is too large, installing and splitting the dex file is a complex process that may cause no response (ANR) errors to the application. In this case, you should minimize the size of the dex file and delete useless logic, rather than relying entirely on multidex. Before Android 4.0 (API Level 14), multidex may not run due to the Dalvik linearalloc bug (problem 22586. If you want to run the Android system version earlier than Level 14, make sure that the test is complete and used. The application uses the multiedex configuration, resulting in a relatively large memory usage. Of course, it may also cause the dalvik virtual machine to crash (issue 78035 ). For projects with complicated applications and many libraries. Multidex may cause the dex file functions of different dependent projects to call each other and the methods cannot be found. Optimize multidex Development and Construction

A multidex configuration greatly increases the complexity of building, signing, and packaging system apk. This means that every build process is quite time-consuming.

To speed up our development and build processes, we can create a development flavor and production flavor in Gradle productFlavors to meet our different build needs.

The following is a column that demonstrates how to set these flavors in the Gradle build file:

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'}

After you complete the configuration modification, you can configure productFlavor and buildType to use the devDebug variant app. With these variants, you can set proguard disable and multidex enable for testing.

These configurations require the following operations on the Android Gradle plug-in:

Before subcontracting, compile each module in the application including the dependent project. This step is called pre-dexing. The most important thing to include each dex file is that the main dex file will not be split. To ensure the computing speed.

This setting ensures that our final report uses the multidex mode without affecting the testing efficiency of our usual development.

Use the variant App in Android Studio

It is very convenient to use the multidex tool to build a variant App. Android Studio allows us to select this variant of the build method interface.

Two steps are required to build a variant app using Android Studio:

Open the variant editing window and select the favorites option. Click to compile different variants, as shown in

/*
* @ Author zhoushengtao (Zhou Shengtao)
* @ Since 10:31:00, January 1, September 9, 2015
* @ Weixin stchou_zst
* @ Blog http://blog.csdn.net/yzzst
* @ Exchange and learning QQ group: 341989536
* @ Private QQ: 445914891
/

Copyright Disclaimer: Reprint Please note: http://blog.csdn.net/yzzst. This article is the original article of the blogger and cannot be reproduced without the consent of the blogger.

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.