Migrating to 3.0
SDK 3.0.0 moves the Data SDK's storage from Realm Java to Room. Realm Java has reached its end of
support and gets no more fixes, security fixes included; Room is part of Android Jetpack,
maintained and patched by Google. The storage change removes the Realm types from the public API,
so 3.0.0 is a major version. It is also published as 3.0.0-kotlin2.2.21.
Most apps change their build file and one or two lines of code, or none. This page says what to change, what happens to your users' data, how to encrypt the database, how to leave the Realm importer out, how the licence check changed, and which other changes to test.
The short list, for an app that already uses the data module with its licence key:
- Check the build requirements below (
minSdk23,compileSdk37, JDK 21, Kotlin). - Declare the SDK through its BOM.
- Fix the few places the table in What to change in your code names.
- Add a
LicenceListener, and make sure your phones reach the Corsano cloud at least every two days (The licence check). - Decide about firmware 9.50 before you ship (Other changes to test).
Before you upgrade
Check your build against these requirements first.
| 2.3.0 | 3.0.0 | |
|---|---|---|
minSdk | 21 (ui: 23) | 23 (Android 6.0): the data module needs it, and every app needs the data module |
compileSdk | 36 (data, ui: 37) | 37 for every module |
| JDK | 17 | JDK 21 toolchain: the artefacts are Java 21 class files, so your Android Gradle Plugin must be a version that can read them |
- Kotlin.
3.0.0needs Kotlin 2.3 or later in your project. A project on Kotlin 2.2 uses3.0.0-kotlin2.2.21, built from the same sources. - An app below
minSdk23 cannot take 3.0.0. SDK 2.x gets no further releases. - A licence key, also for Bluetooth only. An app that uses
com.corsano.sdk:ble(ordfu) withoutcom.corsano.sdk:dataran without a licence key up to 2.3.0. From 3.0.0 it is locked from the start: see The SDK needs a licence key. - No downgrade. After the first start of 3.0.0 the data is in the Room database, and the old Realm file is deleted at the next start once it was verified. An app that goes back to SDK 2.x finds no data. Do not ship a downgrade.
Declare the SDK through its BOM
From 3.0.0 all modules of the SDK (core, ble, data, dfu, ui, legacy-realm,
dfu-archive) must be of one version: two different ones fail at runtime with
NoClassDefFoundError or NoSuchMethodError. The bill of materials, com.corsano.sdk:bom, sets
that version. Declare the BOM once and the modules without a version:
dependencies {
implementation(platform("com.corsano.sdk:bom:3.0.0"))
implementation("com.corsano.sdk:ble")
implementation("com.corsano.sdk:data")
implementation("com.corsano.sdk:dfu")
}
On Kotlin 2.2 the BOM is com.corsano.sdk:bom:3.0.0-kotlin2.2.21. Maven imports it:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.corsano.sdk</groupId>
<artifactId>bom</artifactId>
<version>3.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Do not pin one module to another version with strictly, a force or a resolution strategy:
that splits the SDK again.
What to change in your code
| If your code… | in 3.0.0 | change |
|---|---|---|
reads the models (MetricHrv, SleepSummaryModel, …) and their fields | unchanged: same class names, package com.corsano.sdk.data.external.realm.models, fields and types | none (recompile) |
reads a list field (heartRateSlots, sleepSlots, slots, measurements, …) with for, size, get, firstOrNull | the 9 lists are MutableList instead of RealmList | none |
declares a RealmList or creates one with RealmList() | RealmList is gone from the API | MutableList / mutableListOf() |
calls isManaged, isValid, deleteFromRealm() or addChangeListener on a model | the models are plain classes, always detached copies | read again through the repository; delete through the repository |
uses RealmDatabase or Manager.realmDatabase | removed, with no replacement: the database is internal | use the repositories |
constructs EcgRepository, NibpCalibrationRepository, SpotMeasurementRepository or WearingOptimizationRepository | their constructors are internal | Manager.ecgRepository, nibpCalibrationRepository, spotMeasurementRepository, woRepository |
calls LocalSetting(realm, key) | replaced, and read asynchronously | LocalSetting.load(key, result = { setting -> }) or the suspend LocalSetting.load(key). Pass result by name: the last parameter is the optional onError. The answer comes on the callback scheduler once the import of the 2.x file is over, and onError gets the reason when the database is Unreadable. value, setNew, get, has, get*Value are unchanged |
calls SleepSettings(realm) | replaced, and read asynchronously | SleepSettings.load(result = { settings -> }) or the suspend SleepSettings.load() |
| added R8 / ProGuard keep rules for the SDK's Realm classes | not needed | remove them |
| applies the Realm Gradle plugin only for the SDK | not needed | remove it |
The repositories, their *Database interfaces, the *Updated listeners and the managers keep their
signatures. The copyFromRealm parameters are still there and are ignored: every model returned is
a copy.
Because every model is a copy, changing a field of a model does not change the database, and a
model you hold does not update itself. Read again through the repository when a *Updated
listener tells you there is new data.
What happens to your users' data
Nothing for your app to call. On the first start of 3.0.0 (CorsanoSdk.initialize):
- The SDK opens its Room database,
corsano-sdk-local.dbin the app's database directory (Context.getDatabasePath), with-waland-shmfiles next to it. - If the Realm file of SDK 2.x,
corsano-sdk-local-raw.realminContext.filesDir, is there, the importer copies it table by table on a thread of the SDK's own, unsynced rows first, and verifies every table: every Realm key is in Room, the unsynced counts agree, a sample of up to 1,000 rows matches field for field, and every list has as many items as in the file (in the file's order). The importer only reads the file. - A repository call made during the import waits on the SDK's data thread, never on the main thread, and then answers with the imported data.
- After a verified import the file is renamed
corsano-sdk-local-raw.realm.imported, and deleted at the next start.
If something goes wrong, nothing is lost:
| Case | What the SDK does | databaseState |
|---|---|---|
| An import attempt fails verification or cannot read the file | keeps the file as it is, opens the database to the app, retries at the next start (inserting only what Room lacks, so it never overwrites what the app wrote since) | ImportFailed(file, attempt, reason) |
| The third attempt fails | keeps the file for good as corsano-sdk-local-raw.realm.failed; export it and send it to Corsano | ImportFailed(…, keptAs = "corsano-sdk-local-raw.realm.failed") |
| Less free space than twice the file's size | tries nothing, retries at the next start | ImportFailed(file, 0, "not enough free space…") |
| The importer is left out (below) | keeps the file untouched | LegacyFileWithoutImporter(file) |
| The database file cannot be opened (a wrong key, an encrypted file opened without the factory) | keeps the file unchanged, never deletes it; until it opens, every repository call fails: a suspend call returns the failure, a call with an onError gets it there, and a callback read that takes no onError logs it and answers null (an empty list for an ECG list). A read whose optional onError was left out (LocalSetting.load, SleepSettings.load, Manager.getLegacyImportReport) only logs it and does not call its result. exportData, exportWiffFiles and exportWiffFilesToAppDirectory end in onError, AccWiffParser.run in the listener's onError; startEcg refuses and stopEcg sends the stop anyway | Unreadable(cause) |
A large file takes seconds: 7 unsynced days with a PPG row every second and every other table every minute (735,889 rows, 31 MB) import and verify in under 8 s on an API 28 emulator.
Backups
If your app's backup rules (android:fullBackupContent, android:dataExtractionRules) name the
SDK's Realm file, add databases/corsano-sdk-local.db*. If you encrypt the database with a key
kept in the Android Keystore, exclude the database from backup: a restore on another phone cannot
unwrap the key, and the SDK reports such a file as Unreadable.
Watching the upgrade and checking it
Manager.databaseState reports what the database is doing. You do not have to wait for it before
you call the SDK (calls made during the import wait by themselves), but it lets you show the user
that an update is running and report a failure.
DatabaseState | Meaning |
|---|---|
Opening | The database is being opened. |
Importing(file, table, rowsDone, rowsTotal) | The data of SDK 2.x is being imported. |
Ready | The database is open and any import is over. |
ImportFailed(file, attempt, reason, keptAs) | An import attempt failed; the database is open and usable. See the table above. |
LegacyFileWithoutImporter(file) | The phone holds a Realm file of SDK 2.x but your build leaves the importer out. |
Unreadable(cause) | The database file cannot be opened. |
val manager = DataSdk.getInstance().getManager()
manager.databaseState.addListener(object : ValueUpdated.Listener<DatabaseState> {
override fun onValueUpdated(model: DatabaseState) {
when (model) {
is DatabaseState.Importing -> showUpdating(model.table, model.rowsDone, model.rowsTotal)
DatabaseState.Ready -> hideUpdating()
is DatabaseState.ImportFailed, is DatabaseState.Unreadable,
is DatabaseState.LegacyFileWithoutImporter -> reportToSupport(model)
DatabaseState.Opening -> Unit
}
}
})
// The listener gets the changes; the state right now:
val now = manager.currentDatabaseState
The listener is called on the SDK's callback scheduler (the main thread by default). For your own
verification, getLegacyImportReport() gives, per Realm file, its state (IMPORTING, IMPORTED,
FAILED), attempts and last error, and per table the rows in the Realm file and in the database,
the unsynced counts and whether the table was verified. The report stays after the Realm file is
gone.
val report = manager.getLegacyImportReport() // suspend; a callback variant exists
val file = manager.exportLegacyRealmFile(directory) // a copy of the .failed file, or null
The sample app's "Database" screen (screens/database/DatabaseFragment.kt) shows both.
Encrypting the database
The default is plain SQLite, as unencrypted as the Realm file was. To encrypt, pass a
SupportSQLiteOpenHelper.Factory that encrypts, for example SQLCipher's
(net.zetetic:sqlcipher-android, a dependency of your app, not of the SDK):
System.loadLibrary("sqlcipher")
val dataConfig = DataSdk.Config(
licenceKey = LICENCE_KEY,
// your own key management; see the sample app's SampleDatabaseKey for one way
databaseOpenHelperFactory = SupportOpenHelperFactory(keyBytes),
)
- Load SQLCipher's native library first. Call
System.loadLibrary("sqlcipher")beforeCorsanoSdk.initialize, as above: the factory does not load it, and without it the database cannot be opened (DatabaseState.Unreadable). - The SDK holds no key and has no other copy of the data. If the key is lost (app data cleared, a backup restored on another phone, a Keystore reset), the rows not yet uploaded cannot be read again. Your app owns the key's storage, backup and recovery.
- Choose before the first start of 3.0.0, and keep it. The importer writes through the factory.
A file the factory cannot open is kept and reported as
Unreadable, never deleted or recreated. - Turning encryption on later, for an installation that already has a plain database, is your
app's step before
CorsanoSdk.initialize: SQLCipher'ssqlcipher_export()copies a plain database into an encrypted one. The SDK does not convert files. - The sample app (
database/SampleDatabaseKey.kt) wraps a random 32-byte key with an Android Keystore AES-GCM key and passes it to SQLCipher as a raw key. It is sample code, not SDK API.
Leaving out the importer
com.corsano.sdk:data brings com.corsano.sdk:legacy-realm, the importer, by default, so that an
upgrade cannot strand data because a line was forgotten. It is the only part of the SDK that still
contains Realm (and its native library, librealm-jni.so).
When you may leave it out: when no installation of your app has ever run SDK 2.x or older, so no phone has the SDK's Realm file. A new app that starts on 3.0.0 is the typical case. If your app ever shipped SDK 2.x, keep it: it costs nothing once the import is done.
The cleanest way is an exclusion on the data dependency itself. It sits next to the
dependency it concerns and touches nothing else:
// build.gradle
implementation("com.corsano.sdk:data") { exclude group: "com.corsano.sdk", module: "legacy-realm" }
// build.gradle.kts
implementation("com.corsano.sdk:data") { exclude(group = "com.corsano.sdk", module = "legacy-realm") }
A project-wide configurations.all { exclude group: "com.corsano.sdk", module: "legacy-realm" }
works too, but hides the decision away from the dependency. Check the result with:
./gradlew :app:dependencies --configuration releaseRuntimeClasspath | grep legacy-realm
No output: the importer is out. If a phone still has a Realm file of the SDK, the SDK keeps the file
untouched and reports LegacyFileWithoutImporter; add the module back and the next start imports
it. Leaving the importer out never deletes data.
The licence check no longer crashes your app
Up to 2.3.0 a licence key that was unknown or expired, or a phone whose date was set by hand, made the SDK throw on a background thread a few seconds after every start, which ended your app. From 3.0.0 the SDK locks instead and tells you why:
val config = DataSdk.Config(
licenceKey = LICENCE_KEY,
licenceListener = object : LicenceListener {
override fun onLicenceLocked(error: LicenceError) {
when (error) {
LicenceError.PhoneDateInvalid -> showSetAutomaticDate() // then DataSdk.recheckLicence()
LicenceError.NotConfirmed -> showConnectToInternet() // then DataSdk.recheckLicence()
LicenceError.Unknown, is LicenceError.Expired -> showContactSupport()
LicenceError.NoLicenceKey -> Unit // never told here: see "The SDK needs a licence key"
}
}
override fun onLicenceUnlocked() = hideLicenceMessage()
},
)
or collect DataSdk.licenceState. While locked, everything that reaches the bracelet or produces
new data fails with SdkLicenceException through its usual error channel, and background download
stops. The data already on the phone stays readable, so upload it as usual. The full description
is in Getting Started, Licence Key.
A phone needs a connection that reaches api.health.cloud.corsano.com at least every two
days. No network (LicenceState.Unverified) does not lock while the Corsano cloud confirmed the
key on that phone in the last two days. After two days without a check that confirms it, the next
check that cannot be completed locks with LicenceError.NotConfirmed, until a check confirms the
key. For a key never confirmed on the phone (a new install, or the first start of 3.0.0) the two
days count from its first check that could not be completed. The SDK checks the key at each start
and twice a day in the background when a network is there. If your phones are often offline, also
call DataSdk.recheckLicence() when the network comes back.
| If your code… | change |
|---|---|
| caught the crash with a default uncaught-exception handler | remove that; use licenceListener or licenceState |
treats any onError of a command or a manager as a bracelet problem | check for SdkLicenceException first: retrying does not lift a lock |
switches on DfuError.errorCode | handle DfuError.LICENCE_LOCKED (-32) |
handles BleScanEvent.BleScanFailed | handle errorCode == BleScanFailed.LICENCE_LOCKED (-32): the scan was not started |
The SDK needs a licence key
Up to 2.3.0 only the Data module checked the licence key, so an app with com.corsano.sdk:ble
(and dfu) but without com.corsano.sdk:data ran without one. From 3.0.0 ble and dfu do not
work on their own: an SDK that CorsanoSdk.initialize starts without the Data module is locked
from the start. Scans end with BleScanEvent.BleScanFailed(BleScanFailed.LICENCE_LOCKED),
connect opens no connection, commands fail with SdkLicenceException(LicenceError.NoLicenceKey)
and CorsanoDfu.startDfu fails with DfuError.LICENCE_LOCKED.
If that is your app:
-
Add the Data module next to the BLE one (it needs
minSdk23):implementation("com.corsano.sdk:data") -
Pass your licence key when you initialize the SDK:
CorsanoSdk.initialize(context,CorsanoSdkConfig.Builder().addModuleConfig(DataSdk.Config(licenceKey = LICENCE_KEY)).build(),) -
Keep the Data module's initializer in your manifest: an entry that removes
com.corsano.sdk.data.internal.init.DataSdkInitializerFactory(tools:node="remove") locks the SDK the same way.
You need not call anything else of the Data module. If you have no licence key, contact Corsano.
An app that already initializes DataSdk with its key changes nothing.
Other changes to test
3.0.0 also changes behaviour outside storage and the licence. None of these needs new code in most apps, but each can change what your app or your users see. The Change Log has the full list.
| Area | What changed | What to check |
|---|---|---|
| Firmware | The default firmware of the 287-2B is 9.50 (it was 8.65). needDfu answers true for every bracelet below it, and startDfu(address, hardwareId) installs it. | If your app updates automatically, every bracelet is updated after you ship 3.0.0. This cannot be undone: from firmware 9.42 a bracelet cannot be downgraded to a lower major version (8.x or older). To stay on another version, pass it to startDfu. See DFU SDK. |
| Firmware | No update below 30 % bracelet battery: it ends with DfuError.BRACELET_BATTERY_TOO_LOW (-30). An update Android refuses to start ends with DfuError.START_FAILED (-31) instead of an exception. An aborted update calls onDfuAborted (it called onDfuCompleted). | Handle the two new error codes and onDfuAborted. |
| Connection | A connection attempt gets 45 s (was 15 s). A lost connection is reconnected at once and the bracelet reports CONNECTING straight away. Without BLUETOOTH_CONNECT (Android 12 and later) connect opens no connection instead of crashing. | Timeouts and "connecting" indicators of your own. See Pairing. |
| Scanning | startScan throws IllegalStateException while Bluetooth is off (it threw NullPointerException). | Check that Bluetooth is on before you scan. |
| Commands | Each bracelet has its own command queue. Commands waiting for a bracelet that disconnects now end with an error instead of never answering. | Code that relied on a callback never arriving. See BLE SDK. |
| Enums | CommandId and FileOnWatch have new values. | A Kotlin when over them without an else branch no longer compiles. |
| Summaries | Several summary values were corrected: the heart rate zone times and allActiveTime, the SpO2 slot quality and day average, the skin temperature averages, blood pressure days without a value. | Values your backend compares with earlier days. See Summaries. |
| Sleep | SleepSummaryModel.sleepDuration is REM + light + deep, as documented (it included the time awake). A night's date is midnight of the day it ends. The two sessions of a night the bracelet split are one summary. | Sleep totals are lower than with 2.3.0 for the same night. See Sleep processing. |
| NIBP | startCalibration takes the third cuff measurement itself when the first two are more than 15 mmHg apart. A failed or cancelled calibration puts the bracelet's plan back and closes the session. An open session is reported as ALREADY_RUNNING. | Screens that count the measurements, and code that called stopCalibration after a failure. See NIBP. |
| Grouped reads | groupedBySeconds reads and exports weight SpO2 by its quality 1 to 4 only, sum energy_exp and activityCount, leave the -100 marker out of the temperatures, and give sleep its most frequent state. | Charts and exports built on grouped values. See Grouping rows. |
| Reads | A callback read that fails, for example on an unreadable database, answers null once instead of never. | Code that treats null as "no data". |
| Wearing optimization screen | A failed start no longer hangs the screen; gender is read in any case and UNSPECIFIED is kept; the screen sets a fragment result. | See Wearing optimization. |
| Timestamps | Records dated before 2021-01-01 or more than 10 minutes in the future are dropped instead of stored. | Nothing to change; such rows no longer appear. |
Behaviour kept as it was
- The bucket size of the raw metric repositories' grouped reads: only
MetricActivitygroups bygroupedBySecondsseconds; the other five group the millisecond timestamps into buckets ofgroupedBySecondsmilliseconds. Some values in a bucket changed, see the table above. EmographySummaryRepository.deleteSlotsByTimestampdeletes the emography summaries from that day on (their slots stay), as it did.- Deleting a summary keeps its slots as rows of their own, as Realm did.
Fixed with the move: SpotMeasurementRepository.deleteByTimestampRange and
WearingOptimizationRepository.deleteByTimestampRange now delete the measurements that start in
the range; on Realm they always returned a failure.