> For the complete documentation index, see [llms.txt](https://spice.docs.medtroniclabs.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/android.md).

# Mobile App

The SPICE mobile app is a native Android application (Kotlin) used by field staff. It works offline: data is stored in an encrypted on-device database and synchronised with the backend in the background. The server address is compiled into the app, so you build the app for your own deployment and distribute that build.

Deploy the [backend services](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/server.md) first. You need the public API address of the reverse proxy (for example `https://<api-host>`).

## Toolchain

Versions below come from the project's build files.

| Component                         | Version                                                          |
| --------------------------------- | ---------------------------------------------------------------- |
| Android Studio                    | A current stable release that supports Android Gradle Plugin 9.2 |
| JDK                               | 17 or later (Java 17 is the compile target)                      |
| Gradle                            | 9.6.1, supplied by the Gradle wrapper (`./gradlew`)              |
| Android Gradle Plugin             | 9.2.1                                                            |
| Kotlin                            | 2.4.10                                                           |
| Android SDK                       | Platform 37 (`compileSdk` and `targetSdk` 37)                    |
| NDK                               | 26.1.10909125                                                    |
| Minimum supported Android version | API 23 (Android 6.0)                                             |

Install the Android SDK Platform 37 and the NDK version above from the Android Studio SDK Manager. Gradle is configured to use up to 4 GB of heap (`org.gradle.jvmargs` in `gradle.properties`), so use a build machine with at least 8 GB of RAM.

> The project README mentions Java 18. The build files compile for Java 17, so JDK 17 or later works.

## Get the source

```bash
git clone <your-mobile-repository-url> spice_mobile
cd spice_mobile/<android-project-directory>
```

The Android project is the directory that contains `gradlew`, `build.gradle.kts`, `settings.gradle.kts` and the `app` and `analytics` modules. All commands below run from that directory.

## Configure the build

### Server addresses and keys

The build reads deployment-specific values from a properties file named `environment.properties` in the project root (next to `build.gradle.kts`). The file is listed in `.gitignore`; keep it out of source control and out of shared storage. Gradle injects the values into the app as `BuildConfig` fields:

| Property (per build flavor)  | Becomes                  | Purpose                                                                                                                                                                                                                                                                                                                                                                |
| ---------------------------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<PREFIX>_API_BASE_URL`      | `API_BASE_URL`           | Public API address of your backend, including the scheme and a trailing slash, for example `https://<api-host>/`. All API calls are sent to `<API_BASE_URL>auth-service/...`, `spice-service/...` and `offline-service/...`, matching the [reverse proxy](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/server.md#reverse-proxy-cors-and-cookies) paths |
| `<PREFIX>_ADMIN_BASE_URL`    | `ADMIN_BASE_URL`         | Address of the web portal; used to open the privacy policy page                                                                                                                                                                                                                                                                                                        |
| `<PREFIX>_SALT_KEY`          | `SALT`                   | Key used to hash the password on the device (HMAC-SHA512) before sign-in. It must be the same value that your administrator web portal uses as its password hash key and that your stored password hashes were created with                                                                                                                                            |
| `<PREFIX>_DB_ENCRYPTION_KEY` | `ROOM_DB_ENCRYPTION_KEY` | Passphrase that encrypts the on-device database                                                                                                                                                                                                                                                                                                                        |

`<PREFIX>` is chosen per build flavor. The file contains one block of four properties for each flavor you build:

```properties
# Example for a flavor named "myorg" (all values are placeholders)
MYORG_API_BASE_URL=https://<api-host>/
MYORG_ADMIN_BASE_URL=https://<web-host>/
MYORG_SALT_KEY=<change-me>
MYORG_DB_ENCRYPTION_KEY=<change-me>
```

Treat the salt and the encryption key as long-lived secrets:

* **Do not change the encryption key after you have released the app.** The existing on-device database can no longer be opened with a different key, so users would lose any data that has not yet synchronised.
* **Do not change the salt unless you also re-create the stored password hashes**, otherwise nobody can sign in.
* Use a different encryption key for each environment, and store them in your organisation's secret manager.

### Build flavors

The app module defines product flavors in the `version` dimension (`productFlavors` in `app/build.gradle.kts`). Each flavor sets its own application ID suffix, app name, signing configuration and the four `BuildConfig` fields above. To build for your deployment, add a flavor that follows the same pattern and point it at your properties:

```kotlin
create("myorg") {
    dimension = "version"
    resValue("string", "app_name", "<App name>")
    signingConfig = signingConfigs.getByName("<your-signing-config>")
    buildConfigField("String", "API_BASE_URL", "\"${envProperties["MYORG_API_BASE_URL"]}\"")
    buildConfigField("String", "ADMIN_BASE_URL", "\"${envProperties["MYORG_ADMIN_BASE_URL"]}\"")
    buildConfigField("String", "SALT", "\"${envProperties["MYORG_SALT_KEY"]}\"")
    buildConfigField("String", "ROOM_DB_ENCRYPTION_KEY", "\"${envProperties["MYORG_DB_ENCRYPTION_KEY"]}\"")
}
```

If you install more than one flavor on the same device, give each a unique `applicationIdSuffix` so that they can coexist. The Gradle tasks are named after the flavor: with a flavor `myorg`, the tasks are `assembleMyorgDebug`, `assembleMyorgRelease` and `bundleMyorgRelease`.

### Signing configuration

`app/build.gradle.kts` defines the signing configurations (`signingConfigs`). Each one has a key alias, a key password and a store password read from `environment.properties`, and a keystore file in the `app` directory. A flavor chooses one signing configuration with `signingConfig = ...`. Debug variants of a flavor use the same signing configuration as its release variant, so the keystore and the credentials must be in place for any APK build.

1. Create a keystore for your organisation once and keep it safe. **If you lose it you cannot publish updates to installed apps:**

   ```bash
   keytool -genkeypair -v -keystore <your-keystore>.jks -alias <key-alias> \
     -keyalg RSA -keysize 4096 -validity 10000
   ```
2. Copy the keystore into the `app` directory and update the `signingConfigs` block to reference your file name and your property names.
3. Add the alias, key password and store password to `environment.properties`. Never commit the keystore or its passwords.

### Third-party service configuration

The app module applies a crash-reporting plugin and a third-party services plugin (see the `plugins` block in `app/build.gradle.kts`). The services plugin expects a configuration file at `app/google-services.json`.

## Build

Run these commands from the project root. Replace `<Flavor>` with your flavor name in the Gradle task name (first letter capitalised).

```bash
# Debug APK (for testing; installable on devices and emulators)
./gradlew :app:assemble<Flavor>Debug

# Release APK (shrunk with R8, for direct installation or MDM distribution)
./gradlew :app:assemble<Flavor>Release

# Release App Bundle (for store upload)
./gradlew :app:bundle<Flavor>Release
```

Outputs are written under `app/build/outputs/`:

| Artifact   | Location                                           |
| ---------- | -------------------------------------------------- |
| APK        | `app/build/outputs/apk/<flavor>/<buildType>/*.apk` |
| App Bundle | `app/build/outputs/bundle/<flavor>Release/*.aab`   |

Notes:

* Running `./gradlew assembleDebug` without a flavor builds every flavor. Always use a flavor-qualified task.
* A flavor named `production` has its debug variant disabled; build its release variant instead.
* Release builds are shrunk and obfuscated; keep the generated mapping file (`app/build/outputs/mapping/`) for each release if you analyse crash reports.
* Run the unit tests with `./gradlew :app:test<Flavor>DebugUnitTest :analytics:testDebugUnitTest`.

## Distribute the app

| Option                                               | When to use it               | Notes                                                                                                                                                              |
| ---------------------------------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Managed distribution (mobile device management, MDM) | Organisation-owned devices   | Upload the signed release APK or bundle to your MDM, assign it to device groups and mark it as a required app so that updates install automatically                |
| Direct APK                                           | Pilots and small deployments | Share the signed release APK over a trusted channel (for example your own HTTPS download page). Users must allow installation from that source in Android settings |
| App store                                            | Large or public deployments  | Upload the `.aab` produced by `bundle<Flavor>Release`. Sign it with the upload key your store requires                                                             |

Whichever route you use, serve the API over HTTPS and distribute only builds that you signed with your own keystore.

## Versioning and upgrades

* The app version is set in `defaultConfig` in `app/build.gradle.kts` (`versionName` for display and `versionCode` as an integer). Increase `versionCode` for every release you distribute; Android only installs a build with a higher `versionCode` than the installed one, and it must be signed with the same key.
* On start-up the app asks the backend whether its `versionCode` is still accepted (`POST /spice-service/static-data/app-version`). The backend's `VERSION_CODE` setting is the minimum accepted code. When you publish a mandatory update, raise `VERSION_CODE` on `spice-service` after the new build is available, and older installations are blocked with a message until they update. `VERSION_CHECK_EXEMPT_USERS` lists usernames that skip the check.
* The on-device database is exported as versioned schemas and migrated on upgrade, so users keep unsynchronised data when they install a newer build. Do not change the database encryption key (see above).
* Roll a new release out to a small group first and confirm sync before making it mandatory.

## First launch and initial data load

1. Install the app on a device with network access and open it.
2. Sign in with a user account that exists on the server and is assigned to a facility or area. The app hashes the password with the salt and sends it to `/auth-service/session`.
3. After sign-in the app downloads the configuration it needs: user data, form definitions and metadata (the `/spice-service/static-data/...` APIs), then requests an offline-sync package from `offline-service` and downloads the households, members and follow-ups that belong to the user. The first synchronisation is the largest; use a good connection and keep the app open until it finishes.
4. After the initial load the app can be used without a network connection. Later changes are uploaded and downloaded by background work whenever the device is online.

The sync package is built by `offline-service` from the FHIR data via `fhir-mapper`, and it needs RabbitMQ; if the first sync never completes, check those services first. For loading existing records before go-live, see [Data Import and Migration](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/data-import-and-migration.md).

## Verify that the app syncs with the server

1. Check the server is reachable from the device's network: open `https://<api-host>/spice-service/actuator/health` in the device browser and confirm it reports `UP`.
2. Sign in on a test device with a test user. A wrong server address shows as a network error; a wrong salt shows as a failed sign-in even though the password is right.
3. Watch the backend logs while the app starts its first sync: you should see requests to `auth-service` (session), `spice-service` (static data) and `offline-service` (sync create and status) with successful responses.
4. When the sync finishes, open a household or a member list in the app and confirm it matches what the server holds for that user.
5. Switch the device to flight mode, create a record, switch the network back on and confirm that the record reaches the server (for example, it appears in the web portal or reporting application after sync).
