multidex android что это
Что такое Android MultiDex?
есть много сообщений о MultiDex. Я испытал, иногда, ошибки, решенные в том числе multiDexEnabled true на defaultConfig раздел моей сборки.градля.
но что именно это за функция? Каковы сценарии его использования?
3 ответов
файлы приложений Android (APK) содержат исполняемые файлы байт-кода в виде исполняемых файлов Dalvik (DEX), которые содержат скомпилированный код, используемый для запуска приложения. Исполняемая спецификация Dalvik ограничивает общее количество методов, на которые можно ссылаться в одном файле DEX, 65 536, включая методы платформы Android, методы библиотеки и методы в вашем собственном коде. Преодоление этого предела требует, чтобы процесс сборки приложения настраивается для создания нескольких файлов DEX, известных как многодексная конфигурация.
Итак, функция: она позволяет компилировать ваше сложное приложение. Сценарии для его использования, когда ваше приложение не удается скомпилировать из-за попадания 64K DeX метод ограничения ссылки. Это отображается как ошибка сборки, например:
Это просто
Более Подробное Объяснение!
что заставляет количество ссылок превышать 65,536 пределы?
Методы, написанные вами + методы фреймворка Android + сторонняя библиотека (например, Volley, Retrofit, Facebook SDK и т. д.).
Я читал «где-то»
App Compat 24.2.1 содержит 16.5 K методы
Google Play Services GCM 9.6.1 содержит 16.7 K методов
Поэтому, если вы создали простое приложение Hello world, которое имеет App Compat 24.2.1, вы уже 1/4 пути пересечь ограничение методов single dex
Декс означает исполняемый файл Dalvik, который используется процессором виртуальной машины Google (Dalvik) для обработки приложений Android. Android был построен с небольшими и простыми приложениями в виду, и ограничения на одном исполняемом файле Dalvik закрепили крышу ссылок на код в 65,536 методах. Из-за этой проблемы и того, как машина Dalvik обрабатывает выполнение кода, были некоторые компиляции и вызовы проблемы, пока обезьяна патч или MultiDex интеграция. Многодексная интеграция в Android Studio позволяет разработчикам Android возможность компилировать и выполнять код базы с более чем 65,536 методов!
Русские Блоги
Android Multidex использование и принцип реализации
Android Multidex использование и принцип реализации
В Android файл Dex может хранить до 65536 методов, что является коротким диапазоном типов. Однако с увеличением количества методов приложения, когда файл Dex превышает число 65536 методов, во время упаковки будет выдано исключение.
Чтобы решить эту проблему, Google запустил официальное решение: MultiDex в Android5.0.
1. Используйте
Как пользоваться, лучше всего обратиться к официальной документации Google, подробно написанной:
Вот краткое объяснение:
1. minSdkVersion 21 или выше
Если да android 5.0 Вышеуказанные устройства должны быть установлены только на multiDexEnabled true
2. minSdkVersion 20 или ниже
Если вам нужно адаптировать android 5.0 Требуется следующее оборудованиеБиблиотека поддержки исполняемых пакетов Dalvik
Java-код, наследование MultiDexApplication Или в Application Добавить в MultiDex.install(this);
Во-вторых, принцип MultiDex ниже Android 5.0
Примечание:
Версия, на которой основан исходный код com.android.support:multidex:1.0.3
2.1. Загрузка файлов Dex
Следующее через отслеживание MultiDex.install(this); Исходный код, понять принцип его реализации.
MultiDex.install(this);
трек MultiDex.install(this); Исходный код
Отслеживание MultiDex.doInstallation
Отслеживание MultiDex.doInstallation и просмотр принципа реализации MultiDex
Игнорируя логику извлечения и логику проверки файла dex, следующие три вещи в основном выполняются в приведенном выше коде:
Смотреть ниже MultiDex.installSecondaryDexes Способ понять MultiDex Конкретная реализация
MultiDex.V4.install(loader, files);
Разные версии систем Android имеют разные механизмы загрузки классов, поэтому они делятся на V19, V14 и V4 Установка в трех случаях.
Здесь мы смотрим на исходный код следующего V19
С помощью метода install () в V19 стал ясен вопрос о том, как MultiDex загружает файлы Dex:
2.2 Извлечение файлов Dex
Как упоминалось ранее:
MultiDexExtractor Роль этого инструмента поставить АПК dex Файл извлекается в /data/user/0/com.xiaxl.demo/code_cache/secondary-dexes В каталоге
Метод построения MultiDexExtractor
MultiDexExtractor.load
APK dex Извлечение файла
MultiDexExtractor.performExtractions()
2.3 Другие связанные коды
clearOldDexDir(Context context)
3. Резюме
На данный момент принцип MultiDex установки нескольких dex ясен.
Кроме того, hotfix Технология горячего ремонта проходит определенным образом Вставьте восстановленный dex перед массивом Element [] DexPathList Реализуйте предварительную загрузку отремонтированного класса.
Enable multidex for apps with over 64K methods
When your app and the libraries it references exceed 65,536 methods, you encounter a build error that indicates your app has reached the limit of the Android build architecture:
Older versions of the build system report a different error, which is an indication of the same problem:
Both these error conditions display a common number: 65536. This number represents the total number of references that can be invoked by the code within a single Dalvik Executable (DEX) bytecode file. This page explains how to move past this limitation by enabling an app configuration known as multidex, which allows your app to build and read multiple DEX files.
About the 64K reference limit
Android app (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app. The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536—including Android framework methods, library methods, and methods in your own code. In the context of computer science, the term Kilo, K, denotes 1024 (or 2^10). Because 65,536 is equal to 64 X 1024, this limit is referred to as the ’64K reference limit’.
Multidex support prior to Android 5.0
Versions of the platform prior to Android 5.0 (API level 21) use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get around this limitation, you can add the multidex library to the module-level build.gradle file:
Groovy
Kotlin
To view the current versions for this library, see the information about Multidex on the versions page.
If you aren’t using AndroidX, add the following deprecated support library dependency instead:
Groovy
Kotlin
This library becomes part of the primary DEX file of your app and then manages access to the additional DEX files and the code they contain. More details are below in the section about how to configure your app for multidex.
Multidex support for Android 5.0 and higher
For more information on the Android 5.0 runtime, read ART and Dalvik.
Note: When running your app using Android Studio, the build is optimized for the target devices you deploy to. This includes enabling multidex when the target devices are running Android 5.0 and above. Because this optimization is applied only when deploying your app using Android Studio, you might still need to configure your release build for multidex to avoid the 64K limit.
Avoid the 64K limit
Before configuring your app to enable use of 64K or more method references, you should take steps to reduce the total number of references called by your app code, including methods defined by your app code or included libraries. The following strategies can help you avoid hitting the DEX reference limit:
Using these techniques might help you avoid the need to enable multidex in your app while also decreasing the overall size of your APK.
Configure your app for multidex
If your minSdkVersion is set to 21 or higher, multidex is enabled by default and you do not need the multidex library.
However, if your minSdkVersion is set to 20 or lower, then you must use the multidex library and make the following modifications to your app project:
Modify the module-level build.gradle file to enable multidex and add the multidex library as a dependency, as shown here:
Groovy
Kotlin
If you do not override the Application class, edit your manifest file to set android:name in the tag as follows:
If you do override the Application class, change it to extend MultiDexApplication (if possible) as follows:
Kotlin
Or if you do override the Application class but it’s not possible to change the base class, then you can instead override the attachBaseContext() method and call MultiDex.install(this) to enable multidex:
Kotlin
Caution: Do not execute MultiDex.install() or any other code through reflection or JNI before MultiDex.install() is complete. Multidex tracing will not follow those calls, causing ClassNotFoundException or verify errors due to a bad class partition between DEX files.
At runtime, the multidex APIs use a special class loader to search all of the available DEX files for your methods (instead of searching only in the main classes.dex file).
Limitations of the multidex library
The multidex library has some known limitations that you should be aware of and test for when you incorporate it into your app build configuration:
Code shrinking can reduce or possibly eliminate these issues.
Declare classes required in the primary DEX file
This shouldn’t happen for code that’s accessed directly from your app code because the build tools recognize those code paths, but it can happen when the code paths are less visible such as when a library you use has complex dependencies. For example, if the code uses introspection or invocation of Java methods from native code, then those classes might not be recognized as required in the primary DEX file.
multiDexKeepFile property
Then you can declare that file for a build type as follows:
Groovy
Kotlin
Remember that Gradle reads paths relative to the build.gradle file, so the above example works if multidex-config.txt is in the same directory as the build.gradle file.
multiDexKeepProguard property
The multiDexKeepProguard file uses the same format as Proguard and supports the entire Proguard grammar. For more information about Proguard format and grammar, see the Keep Options section in the Proguard manual.
If you want to specify all classes in a package, the file looks like this:
Then you can declare that file for a build type as follows:
Groovy
Kotlin
Optimize multidex in development builds
A multidex configuration requires significantly increased build processing time because the build system must make complex decisions about which classes must be included in the primary DEX file and which classes can be included in secondary DEX files. This means that incremental builds using multidex typically take longer and can potentially slow your development process.
To mitigate longer incremental build times, you should use pre-dexing to reuse multidex output between builds. Pre-dexing relies on an ART format available only on Android 5.0 (API level 21) and higher. If you’re using Android Studio 2.3 and higher, the IDE automatically uses this feature when deploying your app to a device running Android 5.0 (API level 21) or higher.
Tip: Android plugin for Gradle 3.0.0 and higher include further improvements to optimize build speeds, such as per-class dexing (so that only the classes that you modify are re-dexed). In general, for the best development experience, you should always upgrade to the latest version of Android Studio and the Android plugin.
Groovy
Kotlin
To learn more strategies to help improve build speeds (from either Android Studio or the command line), read Optimize Your Build Speed. For more information about using build variants, see Configure Build Variants.
Tip: Now that you have different build variants for different multidex needs, you can also provide a different manifest file for each variant (so only the one for API level 20 and lower changes the tag name), or create a different Application subclass for each variant (so only the one for API level 20 and lower extends the MultiDexApplication class or calls MultiDex.install(this) ).
Test multidex apps
Kotlin
Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.
How to enable multidexing with the new Android Multidex support library
I want to use the new Multidex support library to break the method limit for one of my apps.
With Android Lollipop Google introduced a multidex support library that makes it easy to multidex.
What steps are needed to use this library and to build my app with multidex support?
14 Answers 14
Edit:
Android 5.0 (API level 21) and higher uses ART which supports multidexing. Therefore, if your minSdkVersion is 21 or higher, the multidex support library is not needed.
Modify your build.gradle :
If you are running unit tests, you will want to include this in your Application class:
Or just make your application class extend MultiDexApplication
For more info, this is a good guide.
The following steps are needed to start multi dexing:
Add android-support-multidex.jar to your project. The jar can be found in your Android SDK folder /sdk/extras/android/support/multidex/library/libs
Now you either let your apps application class extend MultiDexApplication
or you override attachBaseContext like this:
I used the override approach because that does not mess with the class hierarchy of your application class.
Now your app is ready to use multi dex. The next step is to convince gradle to build a multi dexed apk. The build tools team is working on making this easier, but for the moment you need to add the following to the android part of your apps build.gradle
And the following to the general part of your apps build.gradle
More info can be found on Alex Lipovs blog.
Understanding Multidex in Android
So, in this blog, we will learn about Dex and Multidex in Android. Especially, this blog is for those Android developers who get 64K method limit exceeded error while building APK. This error comes due to DEX. So, in this blog, we will try to gain more knowledge about Dex and Multidex in Android.
The timeline of this blog is as follows:
Android Build System
Before moving on to DEX, let’s revise some concepts of the build system of Android. Android compiles the resources and source code of our app and packages them into APKs. Conversion of our project into an APK requires many tools and involves many processes. You can understand the build process with the help of the below diagram:
Image Credit: Android Developer website
The build process of a typical Android App can be summarized as below:
Multidex in Android
In Android, the compilers convert your source code into DEX files. This DEX file contains the compiled code used to run the app. But there is a limitation with the DEX file. The DEX file limits the total number of methods that can be referenced within a single DEX file to 64K i.e. 65,536 methods. So, you can’t use more than 64K methods in a particular DEX file. These 64K methods include Android framework methods, library methods, and methods in our code also. This limit of 64K is referred to as the » 64K reference limit«.
So, if our app exceeds 65,536 methods, we will encounter a build error that indicates our app has reached the limit of the Android build architecture. The error is as follows:
Older versions of the build system report a different error, which also indicates the same problem:
Both the above error are known as 64K reference limit i.e we are trying to use more than 64K methods in our code. So, here comes the role of Multidex support in our Android Project. Next time if you want to use more than 64K methods in your project then you can use the Multidex to achieve this.
If you are getting some type of DEX error then before configuring your app for multidex to enable the use of 64K or more reference methods, you should try to reduce the total number of reference methods that are being used by our app. Try the following strategies to avoid using 64K reference methods:
In the next part of this blog, we will learn how to use the Multidex support for our project that has more than 64K methods.
Enabling Multidex support in Project
Here, we will see how to enable multidex for following:
Note: Follow only one of the following based on the minSdkVersion.
Multidex support for API level lower than 21
For executing app code, versions of Android lower than Android 5.0 (API level 21) use the Dalvik runtime, and the limitation of using Dalvik is that you can’t use more than one classes.dex bytecode file per APK. To overcome this limitation, you will have to add the Multidex support library.
To add the multidex support library to your project for API level lower than 21, add the following dependency in your build.gradle file.
If you aren’t using AndroidX, add the following support library dependency instead:
By adding this library, your app can manage the access of additional DEX files. In other words, if you are having more than 64K methods, then you will be having more than one DEX file and these DEX files will be managed by using this multidex support library.
Then, depending on whether you override the Application class, perform one of the following:
1. If you do not override the Application class, edit your manifest file to set android:name in the tag as follows:
2. If you do override the Application class, change it to extend MultiDexApplication (if possible) as follows:
3. Or if you do override the Application class but it’s not possible to change the base class, then you can instead override the attachBaseContext() method and call MultiDex.install(this) to enable multidex:
You are all set now.
This was all about the API level lower than 21. Now, let’s move to the next one.
Multidex support for API level 21 and higher
Your task becomes easier if you are making an app for Android version 5.0 (API level 21) or higher. API level 21 uses a runtime called ART which supports loading multiple DEX files from APK files. So, you do NOT need to add the support library for multidex in Android 5.0 or higher.
Now, for API level 21 or higher, you need to set multiDexEnabled to true in your module-level build.gradle file, as shown here:
Then, depending on whether you override the Application class, perform one of the following:
1. If you do not override the Application class, edit your manifest file to set android:name in the tag as follows:
2. If you do override the Application class, change it to extend MultiDexApplication (if possible) as follows:
3. Or if you do override the Application class but it’s not possible to change the base class, then you can instead override the attachBaseContext() method and call MultiDex.install(this) to enable multidex:
You are all set now.
Limitations of Multidex support library
A good Android Developer know about the benefits of using some library but a professional developer also knows the limitations of using that library
The multidex support library has some known limitations that we should be aware of before using it in our app. Some of the limitations are:
Code Shrinking can reduce or possibly eliminate these issues.
Conclusion
If you are working on an Android application that includes more than 64K methods then to avoid the 64K reference limit, you can use Multidex in your application. I am sure that after reading this blog, you all are familiar with the Multidex property of Android. So, implement this in your project, but before doing so, make sure that your code is totally shrunk because code shrinking will help in reducing or possibly eliminating the Dex error.