- Qt 6.12
- Using Play Feature Delivery
- Qt 6.12.0 Reference Documentation

# Using Play Feature Delivery

Showcases use of Google Play Feature Delivery on Qt.

This document describes the functionality of the Feature Delivery example. The example uses features supported since Qt 6.11.
Play Feature Delivery can be used on older Qt versions, but creating the application requires manual addition of Android project and copying Qt binaries. Instructions for that are found in chapter Feature Delivery on pre Qt 6.11.

#### What is Feature Delivery?

Play Feature Delivery is a capability offered by Google which essentially allows developers to structure their projects in a way that the Google Play store can split their app content into several downloadable packages. It also gives developers control over how the content is delivered to users. These split software and content packages are delivered to the Google Play store using Android App Bundles (AAB). Google's developer documentation details this feature.

#### Example project: Feature Delivery Map Loader

This simple app uses Play Feature Delivery to serve images to a user when requested. The app can be easily modified to create an app that is over 200MB to test the app size limits and download using a large Feature Delivery module.

##### The App

The application consists of a draggable view and four buttons.

- On Startup Load Map and Show Map Info buttons are enabled.
- When clicked Show Map Info button just shows that there are no information available.
- Load Map initiates loading of the feature module:
  1. Download pop-up is shown, from the pop-up the download can be canceled.
  2. When download completes the pop-up is removed and
  3. Change Map and Remove Map buttons are enabled.
- Remove Map button requests feature module to be uninstalled, disabling enabled buttons.
- When Change Map is clicked it opens a view where a map shown can be changed. In this example feature module consists of only one winter-themed map image.

##### Source folder setup

- fdwintermapmodule: Feature Module
- fdmaploader: The main app
- fdmaploader/storeloader: Feature Delivery JNI interface

##### Feature Delivery interface

The `fdmaploader/storeloader` folder contains interface class `PlayStoreLoader` for the Feature Delivery API. The API is not complete, but contains relevant functions for loading and removing feature modules. Module loading is initiated with a call to `PlayStoreLoader::loadModule`. Status of the process can be monitored with signals provided by `PlayStoreLoaderHandler`. A handle to the callbacks can be obtained with `PlayStoreLoader::getHandler` function. The example API also provides a way to check already installed modules with `PlayStoreLoader::getInstalledModules` function and a option to remove installed modules with `PlayStoreLoader::uninstallModules`.

This example is designed so that a developer can easily add their own content to test the Feature Delivery. To exceed the Play Store maximum package size, map images (It does not need to be map images, but it fits the theme of the example.) can be added to the images folders in `fdmaploader` and `fdwintermapmodule`, the image names must also be added to the `images.qrc` file.

##### Under the hood

The API module consists of two parts. Qt interface (`PlayStoreLoader` and `PlayStoreLoaderHandler`) and java classes that handle calling the Android: Google Split Install Interfaces. Qt interface works mostly as a passthrough for the java classes. Qt interface simplifies the API so, that when feature module is being loaded, Google `SplitCompat` and `SplitInstall` classes and listeners are created and released automatically. In this example parts of the APIs are left out, such as `deferredInstall` and language support.
Qt creates and builds package suitable for Google Play deployment using `qt6_add_android_dynamic_features` when it is defined `CMakeLists`.

     qt6_add_android_dynamic_features(${target_name}
         FEATURE_TARGETS fdwintermapmodule)

CMake function `qt6_add_android_dynamic_features` adds the specific dynamic library as the dynamic feature for the Android application target. it requires QT_USE_ANDROID_MODERN_BUNDLE feature to be enabled. That can be done either as a compile-time flag or set in CMakeLists. The folder where the Java part of the interface resides is added to the build using `qt_add_android_dynamic_feature_java_source_dir`.

On the Example app modules are loaded using `storeloader` interface. Qt `PlayStoreLoader` functions and `PlayStoreLoaderHandler` class work as an intermediate between the example code and Java.

     void PlayStoreLoader::loadModule(const QString & callId,
         const QString &moduleName)
     {
         if (callId.isEmpty() || moduleName.isEmpty())
             return;
         if (!loaderInstance->registerNatives())
             return;
         if (!loaderInstance->loader().isValid()) {
             qCritical("StoreLoader not constructed");
             return;
         }
         loaderInstance->loader().callMethod<void>("installModuleFromStore", moduleName, callId);
     }

Java classes handle calls to the `Split Install` API.

             m_splitInstallManager.startInstall(request)
                     .addOnSuccessListener(sessionId -> {
                         PlayStoreLoaderListener listener = m_listeners.get(callId);
                         if (listener != null)
                             listener.setSessionId(sessionId);
                     })

##### Creating Binaries

Using command line a locally testable AAB package can be built.

Create and enter a build directory to the same level with source directory:

     mkdir build-feature-delivery/ ; cd build-feature-delivery/

Configure:

     path-to-qt-version/path-to-abi/bin/qt-cmake -GNinja -B . -S ../feature-delivery/ -DQT_USE_TARGET_ANDROID_BUILD_DIR=ON -DCMAKE_BUILD_TYPE=Debug

Build:

     ninja aab

##### Testing

The built AAB can be tested locally by using `bundletool` with `--local-testing` parameter. Android: Bundletool Documentation The bundletool `build-apks` command creates apks file which then can be installed on a device or emulator with `install-apks` command

###### Bundletool commands used

Generate APK:s from a bundle:

     bundletool build-apks --bundle=/path/to/bundle.aab --output=/path/to/apk/package.apks --local-testing

Install app to the device:

     bundletool install-apks --apks=/path/to/apk/package.apks

##### Delivering to Play Store

In order to be able to upload the created AAB package to the Google Play Store the package must be signed. For that `jarsigner` can be used. Below is an example jarsigner command to sign the AAB package. See Android: Jarsigner Documentation

     jarsigner -verbose -sigalg SHA256withRSA -digestalg SHA-256 -keystore [path-to-keystore-file].keystore [path-to-aab-file].aab [alias]

#### Feature Delivery on pre Qt 6.11

Versions prior Qt 6.11 does not support Google Play Store compatible package generation. If you are not able to use a Qt version 6.11 or later there is a way to use Google Play Feature Delivery, but it requires manual creation of the Android project, and copying of the Qt binaries to it. Rest of the document have instructions how to achieve that. The instructions may not be 1-to-1 compatible for all environments, but should give good hints to achieve successful Feature Delivery implementation. It is advised to use the example as a basis.

##### Feature Module

Feature modules are build like normal libraries.

- Use Qt Creator to create a C++ shared library.
- Implement features and add resources.
- Build to create .so binaries.

Feature Delivery handles C++ libraries like normal shared libraries that may or may not be available at runtime. Before calls to a library, the availability of one must be checked.

##### Main App (Qt)

- Use Qt Creator to create an app (Qt Quick project template was used here).
- Implement access to the Feature Delivery library. The central class in Google Play Feature Delivery Java library is Android: SplitInstallManager.
- Android template files can be created by using the 'Create Templates' button on QtCreator Projects -> Build&Run -> [target ABI] -> Build Steps -> Build Android APK. Templates are created in the 'android' folder in the project.
- Add Java files to the folder `.../android/src/java/[package...]` and file paths to `CMakeLists.txt`:

       qt_add_executable...
       ...[path]/[java-filename.java]
       ...

- In the example, a Java class was created to handle the calls and callbacks. The Java class would then be accessed from Qt using JNI. Android: Request an on demand module section in the Android documentation has a simple description of how to request a module.
- When adding Java files under the android folder in the project, QT_ANDROID_PACKAGE_SOURCE_DIR property must be added to the `CMakeLists.txt`:

       ...
       set_property(TARGET appFDMainApp APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR
                    ${CMAKE_CURRENT_SOURCE_DIR}/android)
       ...

- Also, the main app `build.gradle` must have dependencies for the feature API: in the dependencies block, replace

       implementation 'androidx.core:core:1.13.1'

  with

       implementation("com.google.android.play:feature-delivery:2.1.0")

- Implement access to the library provided by the feature module. As the Feature Module may or may not be available to the main app, modules are not linked at build time and calls to the module must be resolved at runtime. Example:

       QString MapLoader::loadMapInfo()
       {
           QScopedPointer<QString> resultStr;
           typedef void* (*LoadMapInfoFunc)();
           //Find if wintermap library exists
           mWintermapLibrary.setFileName("fdwintermapmodule");
           if (!mWintermapLibrary.load()) {
               qWarning() << Q_FUNC_INFO << "Failed to load library";
               return QString();
           }
           LoadMapInfoFunc loadMapInfo = (LoadMapInfoFunc) mWintermapLibrary.resolve("loadMapInfo");
           if (loadMapInfo) {
               void* result = loadMapInfo();
               resultStr.reset(static_cast<QString*>(result));
           } else
               qWarning() << Q_FUNC_INFO << "Function loadMapInfo not loaded";

           return *resultStr.data();
       }

- Implement the user interface and other required parts of the main app.

##### Feature Module (Qt)

- Use Qt Creator to create an app (Qt C++ Library project template was used).
- Implement features the module offers.

##### Android Project (Android)

Creating a project for building an Android app bundle for Feature Delivery is based on Android's documentation, mainly:

- Android: Android Feature Delivery Documentation

Create an Android project manually or using Android Studio (Using the 'No Activity' template). The project is modified so that it contains a top-level project and two sub-projects, `app` and `feature-module`. The Android Studio template creates the `app` sub-project and the `feature-module` can be added using File -> New -> New Module template.

The template project requires several modifications:

- Add Feature Delivery plugin to the main level `build.gradle`:

       plugins {
           id 'com.android.application' version '8.5.2' apply false
           id 'com.android.dynamic-feature' version '8.5.2' apply false
           id 'com.android.library' version '8.5.2' apply false
       }

- Add feature module to the `settings.gradle`, change `rootProject.name` if needed:

       ...
       rootProject.name = "name-of-the-root-project"
       include(:app)
       include(:name-of-the-feature-module)

###### app - Sub-project

- Android project requires Qt binaries from the Main App project:
  - Copy native libraries in Qt build: `[build directory]/android-build/libs/[target ABI]` to `app/src/main/jniLibs/[target ABI]`
  - Copy jars in `[build directory]/android-build/libs/` to `app/libs/`
- From the Qt build, also contents of the `res` folder, `AndroidManifest.xml`, and `local.properties` are copied to respective places in the Android project.
- Add file `feature_names.xml` to the `app/src/main/res/values` folder containing a string for the feature module:

       <?xml version="1.0" encoding="utf-8"?>
       <resources>
           <string name="feature_module_name">name-of-the-feature-module-here</string>
       </resources>

- Add file `keep.xml` to `app/src/main/res/raw` folder containing:

       <?xml version="1.0" encoding="utf-8"?>
       <resources xmlns:tools="http://schemas.android.com/tools"
           tools:keep="@string/feature_module_winter_map"
           tools:discard="" />

##### Modifications to app sub-project build files

Build files copied to the Android project need some modifications.

###### app - Sub-project

build.gradle

- Remove `buildScript` and `repositories` blocks.
- Android block in main app's `build.gradle` requires some modifications:
  - `defaultConfig`
  - `packagingOptions`
  - `dynamicFeatures`
  - `sourceSets`
  - `aaptOptions`
  - `dependencies`

     android {
     ...
       defaultConfig {
       ...
         applicationId "your-project-name-here"
       ...
       }
       packagingOptions.jniLibs.useLegacyPackaging true

       dynamicFeatures = [":your-dynamic-feature-name-here"]

       sourceSets {
         main {
           manifest.srcFile 'src/main/AndroidManifest.xml'
           java.srcDirs = [qtAndroidDir + '/src', 'src', 'java']
           aidl.srcDirs = [qtAndroidDir + '/src', 'src', 'aidl']
           res.srcDirs = [qtAndroidDir + '/res', 'res']
           resources.srcDirs = ['resources']
           renderscript.srcDirs = ['src']
           assets.srcDirs = ['assets']
           jniLibs.srcDirs = ['src/main/jniLibs/']
         }
       }

       // Do not compress Qt binary resources file
       aaptOptions {
         noCompress 'rcc'
       }
     ...
     }

     dependencies {
     ...
       implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
       implementation 'com.google.android.play:feature-delivery:2.1.0'
       implementation libs.material
     ...
     }

Also add signing configuration to android block:

     android {
     ...
       signingConfigs {
         release {
           storeFile file("/absolute/path/to/the/keystore.jks")
           storePassword "myStorePassword"
           keyAlias "myKeyAlias"
           keyPassword "myKeyPassword"
         }
       }
       buildTypes {
         release {
           signingConfig signingConfigs.release
           ...
         }
       }
     ...
     }

gradle.properties

Qt has added project variables to `gradle.properties`. Change the value of `androidPackageName` if needed.

AndroidManifest.xml

- Remove `package`:

       ...
       <manifest
       ...
         android:package... <--remove
       ...
       >
       ...

- Change `label` and `android.app.lib_name` if needed:

       ...
       <application ...
         android:label=" ...
         <activity ... >
           <meta-data android:name="android.app.lib_name" android:value=" ...
           />
       ...

###### feature-module - Sub-project

App and feature modules are created as sub-projects for the top-level Android project. The folder and file structure is similar to the app sub-project.

- Feature-module binaries from the Qt build are copied to the `[name-of-feature-module]/src/main/jniLibs/`
- Like in the main app, `src/main/res/` folder should have `xml` and `values` folders containing `qtprovider_paths.xml` and `libs.xml` respectively. Both files can be copied from the app project.
- If `src/main/res/` folder contains drawable or mipmap folders and the feature does not require them, they can be removed.
- In the feature module `src/main/res/values` should not contain `app_name` field. In simple projects where strings.xml is not needed for other uses, it can be removed.
- `libs.xml` contains only the name of the feature module:

       ...
           <array name="load_local_libs">
               <item>name-of-the-feature-module-here</item>
           </array>

           <string name="static_init_classes"></string>
           <string name="use_local_qt_libs">0</string>
           <string name="bundle_local_qt_libs">0</string>
       ...

- `AndroidManifest.xml` is added to the `src/main/` directory:

       <?xml version="1.0" encoding="utf-8"?>
       <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           xmlns:dist="http://schemas.android.com/apk/distribution">

           <dist:module
               dist:instant="false"
               dist:title="@string/feature_module_title_string">
               <dist:delivery>
                   <dist:on-demand />
               </dist:delivery>
               <dist:fusing dist:include="false" />
           </dist:module>
           <!-- This feature module does contain code. -->
           <application android:hasCode="true"/>
       </manifest>

- Feature module `build.gradle` is quite similar to the one from the app project, with some changes. Here's an example:

       plugins {
           id 'com.android.dynamic-feature'
       }

       dependencies {
           implementation project(':app')
           implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
           implementation 'com.google.android.play:feature-delivery:2.1.0'
       }

       android {

           namespace = androidPackageName
           compileSdk = androidCompileSdkVersion
           ndkVersion androidNdkVersion

           // Extract native libraries from the APK
           packagingOptions.jniLibs.useLegacyPackaging true

           defaultConfig {
               minSdkVersion qtMinSdkVersion
               targetSdkVersion qtTargetSdkVersion
           }

           sourceSets {
               main {
                   manifest.srcFile 'src/main/AndroidManifest.xml'
                   resources.srcDirs = ['resources']
                   renderscript.srcDirs = ['src']
                   assets.srcDirs = ['assets']
                   jniLibs.srcDirs = ['src/main/jniLibs/']
              }
           }

           compileOptions {
               sourceCompatibility JavaVersion.VERSION_17
               targetCompatibility JavaVersion.VERSION_17
           }

           // Do not compress Qt binary resources file
           aaptOptions {
               noCompress 'rcc'
           }
       }

- `gradle.properties` file can be copied over from the app sub-project, change the `androidPackageName` to the feature module package.

##### Building and deployment

AAB bundle can be built from the command line using gradle wrapper: `./gradlew` bundle The produced AAB will be in `build/outputs/bundle/release` (or `debug`) folder. The AAB can then be copied to the Google Play Store and released for testing. Testing can also be done locally by using `bundletool` with `--local-testing` parameter.

Example project @ code.qt.io