Android Sub-package Multidex principle Detailed

Source: Internet
Author: User

The background of Multidex's production

When the Android system installs an application, one step is to optimize for Dex, a process that has a dedicated tool to handle, called dexopt. The execution of the dexopt is performed when the Dex file is loaded for the first time. This process generates a Odex file, which is optimised Dex. Executing Odex is much more efficient than directly executing the Dex file.

But in the early days of Android, Dexopt had a problem, dexopt would retrieve the method ID of each class, and there would be a list structure inside. However, the length of the list is saved with a short type, resulting in no more than 65,536 method IDs. When a project is large enough, it is clear that the upper limit of this method is not enough. Although dexopt fixed this issue in the new version of Android, we still need to be compatible with the low-version Android system.

In order to solve the problem of the limit of the number of methods, the Dex file needs to be split into two or more, to this end, Google launched the Multidex compatibility package, with Androidstudio implementation of an APK contains multiple Dex features.

Brief principles of Multidex

We have two Dex files in the APK as an example, and the second Dex file is Classes2.dex.

    1. After the applicaion is instantiated, the Compatibility Pack checks whether the system version supports multidex,classes2.dex whether it needs to be installed.
    2. If required, the Classes2.dex is extracted from the APK and copied to the app's sandbox directory.
    3. Classes2.dex is injected into the current ClassLoader by reflection.

The official documentation is introduced below.

Https://developer.android.com/tools/building/multidex.html#about
The author, for official documents translation is as follows:

Build apps with more than 65K methods

As Android devices evolve, the size of the app will grow larger and bigger. When we are developing the app, we usually encounter the following error when compiling our project due to the size of the report and the reason for referencing the library:

totomethod ID not in [0, 0xffff]:65536

Of course, there are some system devices will appear the following log information, but the feedback is the same problem:

131000max65536.tryusing--multi-dex option.

These two error conditions show a common number: 65536. This number, which indicates that you have more than 65,535 function methods in a DEX package.

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

Let's talk about how to solve this problem in detail.

About 65K Method Limitations

We know that executable swords in Android are stored in the Dex file, which contains compiled code to run your application. Dalvik virtual machines have a method-limited specification for executable Dex files, that is, the total number of methods for a single Dex file is up to 65536.

These include:

    • Reference to the Android framework method
    • The Library method
    • The way we write our own code.

To break the limit of this method number, we propose a scenario-generating multiple Dex files. This scenario for multiple Dex files is also known as the Multidex scenario configuration.

Multidex supports versions prior to Android 5.0
Before the Android5.0 version of the platform, Android was using the program code executed by Dalvik runtime. By default, the limit is applied to a single classes.dex.

Dalvik byte-code files per apk. To circumvent this limitation, you can use the Multidex support library to become the main part of your application and to manage the Dex files to get additional Dex files that contain the code.

Multidex supports Android 5.0 and later
Android 5.0 and higher runtime such as art, natively support loading multiple Dex files from the app apk file. Art supports precompiled applications when you install the scan class (.. )。 Dex files are compiled into a single Android device to execute the. oat file.

Avoid 65K restrictions

When you are sure to use Multidex's subcontracting strategy, please make sure your code is good. You also need to do the following steps:

    • Remove some unused import and library
    • Use Proguard to remove some unused code
Use Multidex with Gradle configuration

The Android Gradle plugin supports the use of Multidex at the start of Android Build Tool 21.1.

Setting up your application development project using the Multidex configuration requires you to make some modifications to your application development project. :

    • Modify the configuration of the Gradle to support Multidex
    • Modify your manifest. Let IT support the Multidexapplication class

Modify the Gradle build as follows:

android {    21    "21.1.0"    defaultConfig {        ...        14        21        ...        // Enabling multidex support.        multiDexEnabled true    }    ...}dependencies {  ‘com.android.support:multidex:1.0.0‘}

Tips: You can multidexenabled in the Gradle configuration file in Defaultconfig,
BuildType, productflavor option settings.

In the manifest file, add a reference to the Multidexapplication class as follows:

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

Of course, if you rewrite application, make a change to the way you inherit your custom application.

Limitations of the way of Multidex

Although we drive Multidex is a great thing, but Multidex still has its own limitations, we have to develop testing before we have to understand the limitations of what:

    1. If the two dex files are too large, installing the split Dex file is a complex process that may cause an application to be unresponsive (ANR) errors. In this case, you should try to reduce the size of the Dex file and remove the useless logic instead of relying entirely on multidex.
    2. Before the Android 4.0 device (API level 14), Multidex is probably not working because of the Dalvik linearalloc bug (Problem 22586). If you want to run an Android system version prior to level 14, make sure that you test and use it thoroughly first.
    3. The application uses Multiedex configuration, which results in larger memory usage. Of course, it may also cause a crash of the Dalvik virtual machine (issue 78035).
    4. For applications that are more complex, there are more library projects. Multidex may cause the Dex file functions between different dependent projects to call each other and cannot find a method.
Optimize Multidex development and build

A multidex configuration, the system apk build, signature, packaging complexity greatly increased. This means that every time you build the process is time-consuming.

In order to speed up our development and speed up the process of building, we can create a development flavor and production flavor in Gradle productflavors to meet our different building needs.

Here is a column sub-demonstration of how we set these flavors in the Gradle build file:

Android {productflavors {//Define separate dev and prod product flavors. dev {//dev utilizes minsdkversion = +To allow the Android Gradle plugin//to Pre-dex per module and produce an APK the can is tested on            Android Lollipop without time consuming Dex merging processes. Minsdkversion +} PROD {//the actual minsdkversion forThe application. Minsdkversion -}    }...Buildtypes {release {runproguard true proguardfiles getdefaultproguardfile (' Proguard-android.txt '),' Proguard-rules.pro '}}}dependencies {Compile' com.android.support:multidex:1.0.0 '}

After you have completed the configuration changes to the injury, you configure Productflavor and BuildType to use the Devdebug variant app. With these variant apps, you can set Proguard Disable, multidex enable to facilitate our testing.

These configurations require the following actions for the Android Gradle plugin:

    1. Before subcontracting, each module in the compiled application includes a dependent project, which is called pre-dexing.
    2. Include each of the Dex files
    3. Most importantly, no slicing is done for the main dex file. To ensure the calculation speed.

This setting ensures that our final report is a multidex mode without affecting the efficiency of the tests we develop.

Use the Variant app in Android studio

It is very convenient to build variant apps using the Multidex tool. The Android studio allows us to choose the interface for this variant build method.

Building a Variant app using Android studio to build "Devdebug" requires two steps:

    • Open the Variant edit window and select the Favorites option.
    • Click to compile the different variants as shown in

/*
* @author Zhoushengtao (Zhou San)
* @since September 9, 2015 10:31:00
* @weixin stchou_zst
* @blog http://blog.csdn.net/yzzst
* @ Exchange Learning QQ Group: 341989536
* @ Private qq:445914891
/

Copyright NOTICE: Reprint please mark: Http://blog.csdn.net/yzzst. This article for Bo Master original article, without Bo Master permission not reproduced.

Android Sub-package Multidex principle Detailed

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.