The Android Developer Challenge is back! Submit your idea before December 2.

An Android App Bundle is a new upload format that includes all your app’s compiled code and resources, but defers APK generation and signing to Google Play.

Google Play’s new app serving model, called Dynamic Delivery, then uses your app bundle to generate and serve optimized APKs for each user’s device configuration, so they download only the code and resources they need to run your app. You no longer have to build, sign, and manage multiple APKs to support different devices, and users get smaller, more optimized downloads.

Additionally, you can add dynamic feature modules to your app project and include them in your app bundle. These modules contain features and assets that you can decide not to include when users first download and install your app. Using the Play Core Library, your app can later request to download those modules as dynamic feature APKs, and, through Dynamic Delivery, Google Play serves only the code and resources for that module to the device.

Watch the following video for an overview of why you should upload your app using Android App Bundles.

Publishing with Android App Bundles also increases the app size limit to 150MB without having to use APK expansion files. Keep in mind, this limit applies only to the actual download size, not the publishing size. So, users can download apps as large as 150MB and, with dynamic delivery, all of that storage is used for only the code and resources they need to run the app. When you combine this with support for uncompressed native libraries, larger apps, such as games, can reduce disk usage and increase user retention.

If you're using Android Studio 3.2 or higher, most app projects require little effort to support Dynamic Delivery, and you can build an Android App Bundle in just a few clicks. However, adding dynamic feature modules requires a little more effort and possibly refactoring your app.

This page describes the steps to get started building Android App Bundles and describes some important concepts related to app bundles and Dynamic Delivery.

Get started

To build app bundles and support Dynamic Delivery, follow these steps:

  1. Download Android Studio 3.2 or higher—it's the easiest way to add dynamic feature modules and build app bundles.

  2. Add support for Dynamic Delivery by including a base module, organizing code and resources for configuration APKs, and, optionally, adding dynamic feature modules.

  3. Build an Android App Bundle using Android Studio. You can also deploy your app to a connected device from an app bundle by modifying your run/debug configuration and selecting the option to deploy APK from app bundle. Keep in mind, using this option results in longer build times when compared to building and deploying only an APK.

    • If you're not using the IDE, you can instead build an app bundle from the command line.
  4. Test your Android App Bundle by using it to generate APKs that you deploy to a device.

  5. Enroll into app signing by Google Play. Otherwise, you can't upload your app bundle to the Play Console.

  6. Publish your app bundle to Google Play.

The Android App Bundle format

An Android App Bundle is a file (with the .aab file extension) that you upload to Google Play to support Dynamic Delivery.

App bundles are signed binaries that organize your app’s code and resources into modules, as illustrated in figure 1. Code and resources for each module are organized similarly to what you would find in an APK—and that makes sense because each of these modules may be generated as separate APKs. Google Play then uses the app bundle to generate the various APKs that are served to users, such as the base APK, dynamic feature APKs, configuration APKs, and (for devices that do not support split APKs) multi-APKs. The directories that are colored in blue—such as the drawable/, values/, and lib/ directories—represent code and resources that Google Play uses to create configuration APKs for each module.

Figure 1. The contents of an Android App Bundle with one base module and two dynamic feature modules.

The following list describes some of the app bundle’s files and directories in more detail:

  • base/, feature1/, and feature2/: Each of these top-level directories represent a different module of your app. The base module for your app is always contained in a base directory of the app bundle. However, the directory for each dynamic feature module is given the name specified by the split attribute in the module’s manifest. To learn more, read about the Dynamic feature module manifest.
  • BUNDLE-METADATA/: This directory includes metadata files that contain information useful for tools or app stores. Such metadata files may include ProGuard mappings and the complete list of your app's DEX files. Files in this directory are not packaged into your app's APKs.
  • Module Protocol Buffer (*.pb) files: These files provide metadata that helps describe the contents of each app module to app stores, such as Google Play. For example, BundleConfig.pb provides information about the bundle itself, such as which version of the build tools were used to build the app bundle, and native.pb and resources.pb describe the code and resources in each module, which is useful when Google Play optimizes APKs for different device configurations.
  • manifest/: Unlike APKs, app bundles store the AndroidManifest.xml file of each module in this separate directory.
  • dex/: Unlike APKs, app bundles store the DEX files for each module in this separate directory.
  • res/, lib/, and assets/: These directories are identical to those in a typical APK. When you upload your app bundle, Google Play inspects these directories and packages only the files that satisfy the target device configuration, while preserving file paths.
  • root/: This directory stores files that are later relocated to the root of any APK that includes the module that this directory is located in. For example, the base/root/ directory of an app bundle may include Java-based resources that your app loads using Class.getResource(). Those files are later relocated to the root directory of your app’s base APK and every multi-APK that Google Play generates. Paths within this directory are also preserved. That is, directories (and their subdirectories) are also relocated to the root of the APK.

Build and deploy Android App Bundles

An app bundle is different from an APK in that you can’t deploy one to a device. Rather, it’s a upload format that includes all your app’s compiled code and resources in a single build artifact. So, after you upload your signed app bundle, Google Play has everything it needs to build and sign your app’s APKs, and serve them to users through Dynamic Delivery.

If you’re using Android Studio, you can build your project as a signed app bundle in just a few clicks. If you're not using the IDE, you can instead build an app bundle from the command line. Then, simply upload your app bundle to the Play Console to test or publish your app with Dynamic Delivery.

Test your app bundle

After you build your Android App Bundle, you should test how Google Play will use it to generate APKs and how those APKs will behave when deployed to a device.

To test your app bundle, use any of the following methods:

Изображение взято с Android Developers

Что же это такое?

Android App Bundle — это формат публикации приложений Google, который поддерживает загрузку частей вашего приложения только в случае необходимости. Это гораздо лучшая альтернатива созданию единого универсального APK для вашего приложения, и все это без рефакторинга кода!?

App Bundles имеют расширение файла .aabaab и являются альтернативой загрузке APK в консоль Google Play. APK вашего приложения генерируется динамически для каждого пользователя при его установке из Google Play Store в соответствии с конфигурацией его устройства. Таким образом, пользователи загружают только те ресурсы и код приложения, которые им нужны.

Следовательно, приводя к меньшему размеру приложения!

В этой статье я расскажу, как привести ваш проект к такому формату.

bapspatil/AndroidAppBundleDemoAndroidAppBundleDemo — Демо-приложение, чтобы показать как реализовать App Bundle в своем приложении.

Преимущества использования App Bundle

  • Меньший размер приложения — меньший размер APK означает, что пользователи получают ваше приложение загружая меньший объем данных!
  • Нет больше нескольких APK. Вам больше не нужно управлять несколькими APK! Консоль Google Play берет на себя создание и подпись APK для вас.
  • Динамические функциональные модули. Функции приложения загружаются только тогда, когда нужны пользователю, то есть по требованию. Эти функции должны присутствовать как разные модули в проекте вашего приложения.
  • Мгновенное включение (в ближайшее время). Пользователи могут мгновенно запускать ваше приложение без установки, по ссылке.

Итак, приступим…

Пожалуйста, обратите внимание, что App Bundle требует Android Studio 3.2 или выше. На момент написания этой статьи последней бета-версией был Android Studio 3.2 Beta 5, поэтому я собираюсь использовать плагин для Gradle 3.2.0-beta05 для этой статьи.

Мы создадим бандл для приложения с базовым модулем (app по умолчанию) и двумя функциональными модулями, которые мы будем загружать динамически (feature1 и feature2). Модули будут содержать функции, которые мы не хотим включать в базовую версию нашего приложения, т.е. пользователь будет загружать их только по мере необходимости.

Вот как получение модулей будет выглядеть для пользователя:

Создаем первый бандл

Шаг 1:

Изменяем файл build.gradle нашего модуля app.

Шаг 2:

Чтобы создать модуль feature1, переходим в File> New> New Module в Android Studio.

Далее выбираем Dynamic Feature Module (модуль динамических функций), который отображается в диалоговом окне, и нажимаем Next.

Следующие шаги:

  • Выберите модуль app в качестве Base application module
  • Укажите feature1 в качестве Module Name
  • Укажите package name(имя пакета) и Minimum API Level(минимальный уровень API) для модуля feature1, а затем нажмите Next.

В разделе Configure On-Demand Options(Настройка параметров по требованию):

  • Укажите Module title(заголовок модуля) как «Feature 1»
  • Установите флажки Enable on-demand и Fusing

Затем нажмите «Готово».

Файл манифеста feature1 должен иметь следующее содержимое после добавления к нему Activity: И файл build.gradle для feature1 должен иметь код ниже в первой строке, так как это динамическая функция:

apply plugin: 'com.android.dynamic-feature'

Для feature2 нужно повторить предыдущие 2 шага

Шаг 3:

Вернитесь к файлу build.gradle вашего приложения и проверьте, объявлены ли динамические функции как показано ниже:

Шаг 4:

Теперь перейдите в файлы build.gradle модулей feature1 и feature2 и проверьте, добавлен ли модуль app в качестве зависимости.

Шаг 5:

Давайте напишем код в модуле app для загрузки модуля feature1, когда он потребуется. Добавьте следующие зависимости в build.gradle модуля app

implementation 'com.google.android.play:core:1.3.4'

В Activity/Fragment, в котором нужно загружать динамическую функцию по требованию, напишите следующий код: Повторите тоже самое для feature2 там, где это требуется

Шаг 6:

Под капотом Android Studio, Gradle и Google Play используют инструмент под названием bundletool для создания App Bundle, который также доступен как инструмент командной строки.

Чтобы создать отладочную версию вашего App Bundle:

Нажмите «Build> Build Bundle (s) / APK (s)> Build Bundle (s), или вы можете сделать это через командную строку следующим образом:

./gradlew :base:bundleDebug

Пакет можно найти по адресу: project-name / app / build / output / bundle /

Чтобы создать подписанную, release-версию вашего App Bundle для загрузки в консоль Google Play:

  1. Нажмите Build > Generate Signed Bundle/APK, затем выберете Android App Bundle и нажмите Далее.
  2. Затем выберете модуль app из раскрывающегося списка Module ?, который является базовым модулем, для которого создан App Bundle
  3. Введите данные своего ключа после выбора хранилища ключей, как обычно, при подписывании APK. На этом этапе я рекомендую проверить флажок Export encrypted key(Экспорт зашифрованного ключа) ☑️. Позже нужно будет загрузить этот зашифрованный файл-ключ в Google Play Console. Нажмите Далее в конце.
  4. Выберетем Destination Folder(папку назначения) и release в Build Types(типах сборки) и все Flavors, для которых вы хотите создать свой App Bundle, а затем нажмите кнопку Finish

Загрузка в Google Play Console

  • Убедитесь, что полностью ознакомлены с программой подписания приложений Google Play
  • Подайте заявку на использование бета-версии динамических функций

Как только вы получите доступ,то сможете опубликовать свой бандл как рабочий вариант!

…Вот и все» Вы закончили создавать ваш первый App Bundle

Перевод статьи «A Practical Guide To Android App Bundle For Beginners»

На недавно прошедшей Google I/O 2018, среди множества нововведений, объявили также о добавлении нового формата приложений.

Этот формат получил название Android App Bundle и представляет собой улучшенный способ сборки вашего приложения. С его помощью можно легко оптимизировать размер приложения, при этом не нужно будет вносить какие-либо изменения в код. Android App Bundle включает весь скомпилированный код и ресурсы, отсеивая затем то, что не нужно конкретному устройству.

Важно! На данный момент Android App Bundle работает только в preview-версии Android Studio. Последняя версия Android Studio 3.2 Canary доступна здесь.

Android App Bundle представляет собой файл (с расширением .aab), который загружается в Google. Каждый бандл включает скомпилированный код и ресурсы для всех модулей приложения и поддерживаемых конфигураций устройств.

Проще говоря, бандлы это подписанные ZIP-файлы, которые упорядочивают код и ресурсы приложения в модули.

Из этих модулей Google Play генерирует различные APK, которые предоставляются пользователям, такие как: базовые APK, dynamic feature APK, конфигурационные APK и (для устройств, которые не поддерживают разделённые APK) мульти-APK. Каталоги, окрашенные в синий цвет, представляют собой код и ресурсы, которые Google Play использует для создания конфигурационного APK для каждого модуля.

Примечание: бандл нужно создавать для каждого уникального приложения или applicationID. То есть, если вы используете несколько product flavor в своём приложении для создания различных APK, и каждая из этих веток использует уникальный applicationID, то вам нужно будет создать отдельный бандл для каждой ветки.

Код и ресурсы для каждого модуля организованы аналогично стандартным APK, и это логично, поскольку каждый из этих модулей может быть сгенерирован как отдельный APK. Ниже можно увидеть более подробное описание некоторых файлов и каталогов Android App Bundle:

  • base/, feature1/, feature2/. Каждый из этих каталогов представляет собой модуль приложения. Базовый модуль приложения всегда содержится в базовом каталоге бандла. Директории же с дополнительными особенностями, каждой из которых присваивается специальное имя, находятся отдельно.
  • файлы Protocol Buffer (.pb). Эти файлы содержат метаданные, которые помогают описать содержимое бандла в магазинах приложений. Например, BundleConfig.pb, находящийся в корневом каталоге бандла, предоставляет информацию о самом бандле, например, какая версия build tools используется для сборки. Другие файлы, такие как recourse.pb и native.pb, описывают, как определённый код и ресурсы должны использоваться для различных конфигураций устройств. Google Play использует эту информацию для генерации APK, оптимизированного для устройства пользователя.
  • manifest/. В отличие от APK, бандлы хранят файл AndroidManifest.xml каждого модуля в отдельном каталоге.
  • dex/. В отличие от APK, бандлы хранят DEX-файлы каждого модуля в отдельном каталоге.
  • root/. Этот каталог хранит файлы, которые позже перемещаются в директорию root любого APK, который включает в себя модуль, в котором находится этот каталог. Например, каталог base/root/ бандла может включать ресурсы Java, которые загружаются приложением с помощью использования Class.getResources(). Эти файлы позже перемещаются в директорию root APK приложения и каждого мульти-APK, которые генерирует Google Play. Пути в этом каталоге также сохраняются, то есть, подкаталоги тоже перемещаются вместе с root.Примечание: если содержимое этого каталога конфликтует с другими файлами и каталогами в корне APK, Play Console отклонит загрузку бандла. Например, вы не сможете включить каталог root/lib/, поскольку он будет конфликтовать с каталогом lib, уже находящимся в APK.
  • res/, lib/, assets/. Эти каталоги идентичны тем, что используются в стандартном APK. При загрузке приложения, Google Play проверяет в этих каталогах и пакетах только те файлы, которые соответствуют конфигурации целевого устройства.

Создание бандла с помощью Android Studio очень похоже на создание APK. Для сборки достаточно выбрать в меню Build — Build Bundle(s)/APK(s) > Build Bundle(s) и IDE создаст бандл для выбранного варианта сборки и разместит его в каталоге //tputs/bundle/.

Если создаётся бандл для debug-версии приложения, Android Studio автоматически подпишет бандл с помощью отладочного ключа подписи. Для загрузки бандла в Google Play он должен быть подписан.

После того, как Android Studio завершит создание подписанного бандла, его можно будет открыть и проанализировать. Анализ бандла позволяет проверить содержимое и работает аналогично APK Analyzer.

Для создания App Bundle IDE использует тот же инструмент с открытыми исходным кодом, называемый bundletool, который Google Play использует для последующего преобразования бандла в подписанные APK.

Прежде чем загрузить бандл в консоль Google Play, его нужно подписать. Чтобы создать подписанный App Bundle, нужно выполнить следующие действия:

  1. Выбрать в меню Build — Generate Signed Bundle/APK.
  2. В появившемся диалоге выбрать Android App Bundle и нажать Next.
  3. В выпадающем списке выбрать модуль, для которого требуется создать бандл, после чего нажать Next.
  4. Предоставить информацию о созданном ключе подписи либо создание нового ключа подписи. Вы можете использовать те же ключи, которые используете для генерации подписи APK.
  5. Если вы хотите, чтобы Android Studio также сохранила ключ подписи в виде зашифрованного файла, то нужно поставить флажок Export encrypted key. Чтобы иметь возможность загружать бандл, необходимо также загрузить этот зашифрованный файл в консоль Google Play и зарегистрировать подписку приложения с помощью Google Play.
  6. Нажать Next.
  7. Выбрать папку назначения для бандла, тип сборки и product flavor проекта.
  8. Нажать Finish.

После того, как Android Studio завершит создание подписанного бандла, его можно будет найти и проанализировать, выбрав соответствующую опцию во всплывающем уведомлении. Если был выбран экспорт ключа подписи, то к нему можно будет быстро перейти, щёлкнув по стрелке вниз в правом нижнем углу всплывающего уведомления, чтобы развернуть его, и затем выбрав Show Exported Key File.

После того, как бандл создан, его можно загрузить в Google Play для проверки, тестирования или публикации приложения. Прежде чем приступить к работе, следует соблюсти следующие условия:

  1. Зарегистрироваться в программе Google Play App Signing.
  2. Если приложение включает dynamic feature modules, то его можно загружать и тестировать через внутренний тестовый трек консоли Google Play. Однако чтобы опубликовать приложение, нужно принять программу Dynamic Feature, которая на данный момент находится в стадии бета-версии.
  3. Google Play поддерживает загрузку приложений размером не более 100 МБ.

Анализ APK с помощью проводника

Когда бандл загружен, Google Play автоматически генерирует разделённые APK и мульти-APK для всех конфигураций устройств, поддерживаемых приложением. В Play Console можно можно использовать App Bundle Explorer для просмотра всех вариантов APK, сгенерированных Google Play; анализа данных, таких как поддерживаемые устройства и экономия размера APK; загрузки созданных APK для тестирования.

Обновление приложения

После загрузки приложения в Play Console, для обновления приложения достаточно повысить код версии, а также создать и загрузить новый бандл. Затем Google Play сгенерирует обновлённые APK с новым кодом версии и будет предоставлять их по мере необходимости.

Использование Android App Bundle даёт большие преимущества для оптимизации APK приложений. С помощью этого способа мы обновили одно из наших приложений, «Менеджер паролей от Wi-Fi сетей», заменив в нём стандартный APK на App Bundle. Таким образом, размер APK файлов уменьшился на целый мегабайт, что является очень хорошим результатом.

Кроме того, Google на данный момент тестирует дополнение к App Bundle, Dynamic feature modules, с помощью которого можно разбивать базовый APK на части, которые будут докачиваться при необходимости, пока что эта технология находится в бета-версии.

Возможно, единственным недостатком банлдов на данный момент назвать необходимость использовать preview-версию Android Studio, однако эта проблема временная.

See how to use App Bundles to reduce the size of the app your user downloads to their device, saving them precious data and storage!

Version

  • Kotlin 1.2, Android 5.0, Android Studio 3

The App Bundle is a new delivery format for Android apps that helps to deliver an optimized version of your APK by just including what your users need, reducing your app size and making your users happier. :]

Normally, when users download your app, they get what is called a universal APK. This is a file that contains all resources for all device configurations, like images, strings, layouts, and more. Users will not need all of them, which wastes space and leaves less room for apps or games. 😿

With App Bundles, your users will receive a special version of your APK that only includes the language, screen density and resources they need per unique user configuration.

Imagine one of your users has selected English as their default language, and that their device supports extra-extra-high-density (aka xxhdpi). Using App Bundles, the Google Play Store is only going to download an APK file with value-en/strings.xml and xxhdpi resources, reducing the required space and cost of the app.

Note: This tutorial assumes you’re already familiar with the basics of Android development. If you are completely new to Android development, read through our Beginning Android Development tutorials to familiarize yourself with the basics. Other pre-requisites include knowledge of using bash/Terminal, Gradle, and a developer account on the Google Play Console.

Space is one major reason why a user will install or uninstall your app. When users download a new app, they have to take two things into consideration: data and storage consumption.

If your app is too big, users may have to uninstall one or more other apps in order to install yours.

Another trade-off is how much data your app is going to cost them, depending on their data plan. Users often have limited mobile data plans, which means that downloading your app may put users in a tricky situation. They will need to decide what’s more important: streaming videos or downloading your app.

You don’t want to be the app that increases their phone bill, right?

Having a light APK will help you to attract new users to your app and keep existing users. :]

Note: To use App Bundles, you need to install Android Studio 3.2 or higher. If you don’t have it, please download it before continuing.

CountOnMe is an app that displays a number from 1 to 10, every time you swipe. You’re going to use it to see how to use App Bundles in practice, by generating and evaluating the content of different APKs.

Download the CountOnMe project using the Download Materials button at the top or bottom of this tutorial. Open the project in Android Studio 3.2 or later by selecting Open an existing Android Studio project on the Android Studio welcome screen:

There is no final project for this tutorial, since you’ll simply use CountOnMe to explore the App Bundle tools in Android Studio.

Before continuing with the tutorial, take a look at the project.

The source code is structured as follows:

  • MainActivity.kt This is the entry point of the app.
  • values default resources in English strings, dimens etc .
  • values-es default resources in Spanish strings, dimens etc .
  • values-fr default resources in French strings, dimens etc .

As you can see in the above image, there are many more files that weren’t mention for brevity. But the main idea is that you can see the different resources that the app has. When you use App Bundles, you’re going to generate different APK versions that only include some of these resources.

App Bundle is a new format called .aab (Android App Bundle), that you upload to the Play Store instead of the traditional apk. With this new format, the Play Store will generate many different variations of your APK, depending on your user’s device configuration.

App Bundles take advantage of a concept called split APK. As its name suggests, a split APK is similar to a normal .apk. The difference is that a split APK file can be broken into separate small pieces, one containing the base code and other small APKs containing the app resources that can be installed later.

The beauty of splits is that the Android operating system treats the app as a whole, and each split is a small fraction that can be added independently. It’s like one app with small Lego blocks to add on.

To see how an App Bundle is structured, you’ll generate one for the CountOnMe app. Go to BuildBuild Bundle(s) / APK(s)Build Bundle(s) in the Android Studio menu.

Android Studio will show you a prompt for where to find the file. Press locate to open the file location in your file system viewer, e.g., the Finder on macOS.

Since an .aab file is just a compressed file, uncompress it to take a look at its content.

In this case, you’ll use the tool unzip, but you can use any similar tool you like. Open Terminal and navigate to the directory containing the app.aab file. Run the following.

  unzip app.aab  

Alright, now you can see the structure of an .aab.

  • base/, feature1/, and feature2/ Top level folder that contains each module of your app. In the case of CountOnMe, you only have one base directory, because you just have one module. The base directory always contains the main module of your app. Each dynamic feature module will have it’s own feature directory.
  • BUNDLE-METADATA/ Metadata files that may include ProGuard mappings and the list of your app’s DEX files. This directory is only going to be available when proguard is enabled.
  • Module Protocol Buffer (*.pb) files Provides metadata that describes the contents of each app module to the Play Store. For instance, BundleConfig.pb provides information about the bundle itself, like which version of the build tools were used to build the App Bundle.
  • dex Contains the DEX files for each module in a separate directory.
  • res, lib, and assets These folders are used in the same way as a typical APK, except that for an App Bundle, they’re used by Google Play to package only the files that satisfy the target device configuration.
  • root This directory stores files that are later relocated to the root of the APK(s) that include the corresponding module.

The only thing you have to do to use an App Bundle is create an .aab and upload it to the Google Play Store. The Play Store will handle everything from creating multiples version of your APK, to selecting the right one for your users.

Go to Android Studio ▸ BuildGenerate Signed Bundle / APK.

Select Android App Bundle and click Next.

Introduce your app signing configuration and click Next.

On the next screen, choose a Destination Folder and Build Type, and then click Finish. Simple. :]

With the availability of App Bundles, you now have some new Gradle tasks to produce an .aab:

Run the bundle task for CountOnMe, from the project root folder, in this case countonme-starter:

  ./gradlew app:bundle  

You will see that the app.aab file is generated at the following path.

  /countonme-starter/app/build/outputs/bundle/debug/app.aab  

You can use the following commands to create the app bundle for a specific build variant.

  ./gradlew modulename:bundleVariant  

Here buildVariant could be the buildDebug or buildRelease task.

The location of the output file will be:

  /modulename/build/outputs/bundleVariant/app.aab  

The same signing process used for traditional APKs is compatible with App Bundles.

To publish your App Bundle to the Play Store, the first thing you need do is enroll in App Signing by Google Play. After enrolling, you can manage your releases as you did with APKs.

After uploading your App Bundle, you have the opportunity to review your release.

The Google Play console will generate all the APKs for your user configurations. A nice tool for visualizing all those APKs is Bundle Explorer.

Go to Release ManagementArtifact library, then select one of the bundles that you have uploaded and click EXPLORE

Now you can see all the savings that an App Bundle provides, and all the APK files that it generated.

You can go even deeper by clicking VIEW DEVICES, and see the specific devices that an APK is going to be delivered to.

The Bundle Explorer can be a great tool while debugging, when you want to know the exact file that a user received on their device.

App Bundles are also available in the Publishing API for automation.

The Google Play Store provides a convenient way to test your App Bundle called Internal Test Track. This is a special track wherein you can invite a closed list of users to test your app.

The Internal Test Track is similar to the Alpha and Beta tracks. The difference is that you don’t have to wait very long with the Internal Test Track, because it’s available almost instantly after you upload your App Bundle file. That helps to ensure that what your users are going to receive is the same as what your QA team is testing.

In the Play Store console, go to Release ManagementApp ReleasesInternal test track

There you can create a list of up to 100 testers.

You can then share the Opt-in URL link with your testers. This link allows the users on the test list to download your app.

Bundletool is a command-line tool that helps you to manipulate Android App Bundles. This is the same tool that the Play Store uses to generate .apk files from a .aab file. Additionally, the source code of Bundletool is available as an open source project on GitHub, in case you want to take a deeper look at its ins and outs.

Bundletool allows you to test locally and simulate the same process that Google Play does to serve your App Bundle to users, in case you don’t want to test through the Play Store.

It’s your turn to play a bit with Bundletool. :]

Go to the Bundletool release page and download the bundletool-all-[LAST-VERSION].jar file into a new directory called testing-app-bundle. Then rename the jar to bundletool.jar, and copy the debug .aab file that you previously generated to this same directory.

After that, you should have a directory similar to this one:

Note: Bundletool is distributed as a .jar file, so to be able to use it, you need to install Java Runtime Environment. Make sure you have JRE installed before going forward. As an Android developer, you likely have a JDK already installed, which includes a JRE.

To execute Bundletool from the command line, you need to use java -jar bundletool.jar followed by any command that you want Bundletool to execute.

Try this with build-apks. This command takes an App Bundle (.aab) file and outputs a set of APKs. To indicate the bundle, you use the argument --bundle, and output is identified with the argument --output.

Open Terminal, navigate to the testing-app-bundle directory and run the following:

  java -jar bundletool.jar build-apks  --bundle=app.aab --output=app.apks  

After executing the command above, you have a file app.apks:

Note: The command above creates a set of unsigned APKs. If you want to install the APKs onto a device, you must also include your app’s signing information, for example:

  java -jar bundletool.jar build-apks  --bundle=app.aab --output=app.apks  --ks=keystore.jks  --ks-pass=  --ks-key-alias=  --key-pass=

Pro-tip: If you use the flag --connected-device, you can generate APKs just for the devices connected to your development machine.

To install your app on a device, you use the command install-apks, which takes an APK set as an input with the argument --apks, then extracts it and installs the corresponding APK on a connected device.

  java -jar bundletool.jar install-apks --apks=app.apks

Internally, Bundletool will read the configuration of the connected device and will select the APK that matches the configuration in order to install it on the device. This is the same matching process that the Google Play Console does when a user requests an app.

Using Bundletool, you can replicate the same process that Google Play uses. This is a great tool for testing locally.

You’ve seen just a small set of things you can do with Bundletool. You can find more in the complete reference.

You’ll now take a closer look at the APK set file app.apks in the testing-app-bundle folder. Change the extension of app.apks to app.zip and uncompress it using your favorite unzipping tool.

Now you have an app directory. Inside this directory there’s a sub-folder called splits. In there, you can find all the APK variations.

Cool! :]

Now, try a small experiment, taking one of these split APKs and comparing it with a traditional APK.

You’ll take the base-es.apk file and open it with the APK Analyzer tool in Android Studio, by going to BuildAnalyze APK.

Note: APK Analyzer is a tool embedded in Android Studio that allows you to inspect the content of an APK file.

Navigate to the splits folder in the test-app-bundle directory you made, choose base-es.apk and click OK.

base-es.apk is a small file of just 5.3 KB, and it only contains the string resources for the Spanish language.

Now for the other side of the coin, a traditional (universal) APK file. A universal APK contains all the resources for every possible device configuration your app supports, and it’s the traditional way to distribute an app.

Go to BuildBuild Bundle(s) / APK(s)Build APK(s):

Then choose the APK file in app/build/outputs/apk/debug:

As you can see above, the universal APK has everything in it! It’s a much bigger 2.6 MB vs 5.3 KB file, like comparing an 🐜 versus an 🐘.

APK Analyzer allows you to diff two APKs, by going to the upper right corner and clicking the Compare with previous APK button, then navigating to and choosing the base-es.apk file:

Here’s the diff between the universal APK and base-es.apk:

Now you see the real power of App Bundles in action!

Another great feature of App Bundles is dynamic delivery, which helps your apps get even smaller!

The idea is that you can split your apps by feature modules in such a way that parts of your app that are not as popular can be downloaded on-demand, only when the user needs them and not as part of your main APK. It’s the same idea as that of downloading resources, but with code instead. Pretty cool! :]

This feature of App Bundles is currently in Beta, so to be used in production you have to opt-in.

Devices on Android 4.4 (API level 19) and lower do not support split APKs, which are the foundation of delivering multiple APK files to devices. Google Play serves a single APK version that includes resources for all languages that your app supports on those Android versions. For backwards compatibility, you don’t have to take any additional steps, since Google Play takes care of everything for you.

Now that you’ve gotten started with App Bundles, you should try using App Bundles with your own apps and publish an Internal track on the Google Play Store. You can also test your App Bundles locally using Bundletool.

To learn more about App Bundles, take a look at the official reference. You can also learn more about App Bundles and Dynamic Delivery with feature modules here.

I hope you enjoyed this introduction to App Bundles. If you have any comments or questions, please join in on the forum discussion below!

Deepanshu Aug 20, 2018 · 5 min read

In Google I/O 2018, a new publishing format has been introduced for Android applications called Android App Bundle. It is a new upload format that includes all your app’s compiled code and resources, but defers APK generation and signing to Google Play. Traditionally, Android apps are distributed using a special file called an Android Package(.apk).

Why should we use this new format?

  • Dynamic Delivery : Google Play’s new app serving model, called Dynamic Delivery, uses your app bundle to generate and serve optimized APKs for each user’s device configuration, so they download only the code and resources they need to run your app. For example, you don’t need other languages strings if you have set English as your default language.
  • No need to manually manage multiple APKs : You no longer have to build, sign, and manage multiple APKs to support different devices, and users get smaller, more optimized downloads. For example, now you don’t have to create multiple APKs for devices with different screen resolutions.
  • Dynamic Feature Module : These modules contain features and assets that you can decide not to include when users first download and install your app. Using the Play Core Library, your app can later request to download those modules as dynamic feature APKs. For example, video calling feature and camera filters can be downloaded later on demand.
  • Reduced APK size : Using Split APK mechanism(explained later), Google Play can break up a large app into smaller, discrete packages that are installed on a user’s device as required. On average, apps published with app bundles are 20% smaller in size.

How to build an app bundle?

You can easily build your app bundle using Android Studio(3.2 Canary 14+) or using command line interface. The generated app bundle will be stored at app/build/outputs/bundle/buildVariant/bundle.aab.

  1. Android Studio : Go to Build > Build Bundle(s)/APK(s) and select Build Bundle(s).
  2. Console :./gradlew bundle

Dynamic Delivery with Split APKs

A fundamental component of Dynamic Delivery is the split APK mechanism available on Android 5.0 (API level 21) and higher. Split APKs are very similar to regular APKs — they include compiled DEX bytecode, resources, and an Android manifest. However, the Android platform is able to treat multiple installed split APKs as a single app.

On the left: a simple app that includes a base APK (B) and some configuration APKs ©. On the right: a more complex app that includes two dynamic feature APKs (D) and corresponding configuration APKs © for download on demand.

Different types of split APKs

  • Base APK : This APK contains code and resources that all other split APKs can access and provides the basic functionality for your app. When the user downloads the app, they always get this APK.
  • Configuration APKs : Each of these APKs includes only native libraries and resources for a given device configuration — screen density, language or CPU architecture. When a device downloads a base or dynamic feature APK, it downloads only the libraries and resources it needs. Add the following code in android {} block to enable language, density, and abi configuration splits
  • Dynamic Feature APKs : Each of these APKs contain code and resources that are not required when your app is first installed, but may be downloaded and installed later.

For devices running Android 4.4 (API level 20) and lower, Google Play automatically serves a single APK that’s optimized for the device’s configuration.

Deploy your app from an app bundle

If you want Android Studio to build and deploy your app from an app bundle:

  1. Select Run > Edit Configurations from the menu bar.
  2. In the left pane of the Run/Debug Configurations dialog, select your desired configuration under the Android App node.
  3. In the dropdown menu next to Deploy, select APK from app bundle.
  4. Under Dynamic features to deploy, check the box next to each dynamic feature module, if any, you want to include when deploying your app.
  5. Click OK.

Testing your app bundle with Google Play Internal Test Track

Before you can upload your app bundle to the Play console you need to generate a signed app bundle. To generate a signed app bundle, proceed as follows:

  1. Select Build > Generate Signed Bundle/APK from the menu bar. In the Generate Signed Bundle or APK dialog, select Android App Bundle and click Next.
  2. In the Module dropdown menu, select the base module of the app you want to generate an app bundle for.
  3. Provide information for an existing key and keystore, or create a new one. This is the same type of key and keystore information you provide when building a signed APK.
  4. If you want Android Studio to also save your signing key as an encrypted file, check the box next to Export encrypted key. To be able to upload your app bundle and take advantage of Dynamic Delivery, you need to upload this encrypted file to the Play Console and enroll in app signing by Google Play.
  5. Click Next and provide a Destination Folder for your app bundle. Select the Build Type and flavors that you want to generate app bundles for.
  6. Click Finish.

Now that you’ve generated a signed bundle, you can upload your app bundle to the Play Console.

Testing your app bundle using BundleTool

Bundletool is the underlying tool that Gradle, Android Studio, and Google Play use to build an Android App Bundle or convert an app bundle into the various APKs that are deployed to devices.

To generate an APK set for all device configurations your app supports from your app bundle, use the bundletool build-apks command

$ bundletool build-apks --bundle= --output=

Only two arguments are required, 1) the path the .aab file and, 2) the directory where the generated apks are stored. Now you can run build-apks.

WARNING: The APKs won't be signed and thus not installable unless you also pass a keystore via the flag --ks.

To deploy your app from an APK set, use the install-apks command and specify the path of the APK set

bundletool install-apks --apks=/MyApp/my_app.apks

References

Android App Bundle | Android Developers

The Android App Bundle is a new publishing format that defers APK generation and signing to app stores. You no longer…

developer.android.com

Your First Android App Bundle

The benefits of Android App Bundles and dynamic features is best seen when working with complex real-world apps that…

codelabs.developers.google.com

Thank You!!!

ОСТАВЬТЕ ОТВЕТ

Please enter your name here
Please enter your comment!