- Qt 6.9
- Using Play Feature Delivery
- Qt 6.9.3 Reference Documentation

# Using Play Feature Delivery

## What is feature delivery?

Google's developer documentation details this feature 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 sofware and content packages are delivered to the Google Play store using Android App Bundles (AAB).

## Example project: FDMapLoader

This 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.

### Build Setup

- fdwintermapmodule: Feature Module project for Qt Creator
- fdmaploader: Main app project for Qt Creator
- fdmaploader-android-project: Android project for compiling Android App Bundle.

### Compile FDWintermapModule - Feature Module

Load the fdwintermapmodule project to Qt Creator, configure it for your target platform, and build.

### Compile FDMapLoader - Main App

Load the fdmaploader to Qt Creator, configure it for your target platform, and build.

### Modify Android Project

- Copy built binaries (.so) files from the feature module and main app build directories to corresponding library directories in an Android project. (`app/src/main/jniLibs/[target ABI]/` and `fdwintermapmodule/src/main/jniLibs/[target ABI]/` respectively)
- Copy other changed files, such as resource files and Java classes. (`.../res/...` and `.../src/main/java/...` folders)
- Build Android project either using Android Studio or from the command line using Gradle wrapper (`./gradlew` bundle)
- For testing, you can create APKs from a bundle and install a local testing version to a device using `bundletool`. Bundletool is a tool provided by Google and we'll cover using it later in this documentation. For testing and releasing, you can upload the bundle to the Google Play Console.

### Add your own content

This example is designed so that 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 folder in FDMapLoader and FDWintermapModule, the image names must alse be added to the `images.qrc` file.

## Create your own

The following sections describe how to create your own project that uses play feature delivery. It is advised to use the example as a basis. In the project, Qt 6.7.2 was used.

### Feature Module

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.

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

### 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 `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. 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:

       typedef void* (*LoadModuleRulesFunc)();
       LoadModuleRulesFunc loadModuleRules =
           (LoadModuleRulesFunc) mFDModuleLibrary.resolve("loadModuleRules");
       if (loadModuleRules) {
           void* result = loadModuleRules();
           QScopedPointer<QString> resultStr{static_cast<QString*>(result)};
       }

- 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 Feature Delivery Documentation
- Android On Demand Modules Workshop

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 {
           store

           \code
     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 from the example project:

       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 {
               resConfig "en"
               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/']
              }
           }

           tasks.withType(JavaCompile) {
               options.incremental = true
           }

           compileOptions {
               sourceCompatibility JavaVersion.VERSION_1_8
               targetCompatibility JavaVersion.VERSION_1_8
           }

           lintOptions {
               abortOnError false
           }

           // 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. Bundletool documentation

#### 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