From 6d031082a3722d9e05320298642ea85c03ae6a74 Mon Sep 17 00:00:00 2001 From: Hadrian Burkhardt Date: Mon, 9 Nov 2026 00:25:56 +0100 Subject: [PATCH] fix: keep the scan's foreground service inside Android's start budget ScanController called stopService() from a Dispatchers.Default coroutine right after startForegroundService(), so a scan that finished at once or a Cancel tap could beat the pending foreground start on the main thread. ScanService then never reached startForeground() and Android killed the process a few seconds later with RemoteServiceException$ForegroundServiceDidNotStartInTimeException - a stack with no app frames. - ScanService enters the foreground in onCreate() and at the top of every onStartCommand(), before the Cancel early-return. - A refused startForeground() (start not allowed, missing service type or permission, rejected notification) is logged instead of crashing, and a notification error can no longer kill the state collector. - The service stops itself when it observes scanning == false; nothing outside it calls stopService() any more. - New Robolectric ScanServiceTest covers onCreate, the idle and cancel paths, a failing startForeground() and the Android 15 onTimeout path. - Version 1.1.2 / versionCode 7: versionCode 6 (1.1.1) is already on a Play track. CHANGELOG, AGENTS.md, codemap, ROADMAP and the release checklist (1.1.2 artefact record and paste-ready notes) are updated. --- AGENTS.md | 23 ++- CHANGELOG.md | 21 +++ app/build.gradle.kts | 4 +- .../fotodup/finder/domain/ScanController.kt | 8 +- .../fotodup/finder/service/ScanService.kt | 139 ++++++++++++++---- .../fotodup/finder/service/ScanServiceTest.kt | 108 ++++++++++++++ docs/PLAY_RELEASE_CHECKLIST.md | 67 +++++++-- docs/ROADMAP.md | 7 +- docs/codemap.md | 16 +- 9 files changed, 336 insertions(+), 57 deletions(-) create mode 100644 app/src/test/java/de/softwareapp_hb/fotodup/finder/service/ScanServiceTest.kt diff --git a/AGENTS.md b/AGENTS.md index d730816..d466c3b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,7 @@ definition of done for this repository. |---|---| | Product | Foto Dup Finder — offline duplicate/near-duplicate photo finder | | Model | **Freemium**: free tier with one AdMob banner, one-time Pro purchase removes ads | -| Current version | `1.1.1` / `versionCode 6` (`app/build.gradle.kts`) | +| Current version | `1.1.2` / `versionCode 7` (`app/build.gradle.kts`) | | Platform | Android, Kotlin + Jetpack Compose, single `:app` module | | Application id | `de.softwareapp_hb.fotodup.finder.free` (debug `.free.debug`); namespace/code package remains `de.softwareapp_hb.fotodup.finder` | | SDKs | `minSdk 26`, `compileSdk`/`targetSdk` 36 | @@ -30,7 +30,8 @@ Roadmap: [`docs/ROADMAP.md`](docs/ROADMAP.md) Release checklist: [`docs/PLAY_RELEASE_CHECKLIST.md`](docs/PLAY_RELEASE_CHECKLIST.md) Privacy policy: [`PRIVACY.md`](PRIVACY.md) -**Current gate:** the freemium release (`1.1.1`) is implemented in code, but the +**Current gate:** the freemium release (`1.1.2`, the foreground-service bugfix on top of +the `1.1.1` freemium build) is implemented in code, but the Play Console work (change the app to free, create `pro_no_ads`, AdMob app/unit, UMP message, Data Safety, Ads/Advertising ID declarations) is manual. Do not describe the app as "ad-free", "no internet" or "paid once" — those claims belong @@ -166,7 +167,9 @@ Never use `./gradlew --offline` for a fresh dependency check, and never commit stuck provider must produce an unreadable photo, not a frozen scan. 5. **The scan is process-scoped.** `ScanController` owns the job and result; the ViewModel mirrors `ScanState`. `ScanService` keeps a `dataSync` foreground - service alive while it runs. + service alive while it runs. It calls `startForeground()` in `onCreate()` and at + the top of every `onStartCommand()`, and **nothing outside it calls + `stopService()`** — the service stops itself when it sees `scanning == false`. 6. **Thresholds are fitted, then clamped.** `DuplicatePolicy` supplies ceilings; `AdaptiveThreshold` fits the pHash cut to the candidate population; exact grouping does not decode anything. @@ -297,8 +300,9 @@ Never use `./gradlew --offline` for a fresh dependency check, and never commit 9. **AOSP emulators do not have Play services.** An empty ad slot or a "purchases unavailable" message there is expected; it is not a code failure. 10. **`versionCode` must increase** for every Play upload. `1.0.2` used 3, the - 1.1.0 internal-testing build used 4, the first 1.1.1 upload used 5, and the corrected - freemium build is 6. Update `CHANGELOG.md` and the release checklist too. + 1.1.0 internal-testing build used 4, the first 1.1.1 upload used 5, the corrected + 1.1.1 freemium build used 6, and the foreground-service fix is `1.1.2` / 7. Update + `CHANGELOG.md` and the release checklist too. 11. **Do not call `navigationBarsPadding()` twice.** The bottom slot owns the inset; `BottomActionBar` must not add it again. 12. **The old paid-app docs are historical.** Do not copy "pay once", "no ads" or @@ -308,6 +312,15 @@ Never use `./gradlew --offline` for a fresh dependency check, and never commit removed by R8 unless `app/proguard-rules.pro` keeps it, producing a release-only crash before `Application.onCreate`. Keep the rule and smoke-test a minified build; debug builds do not reproduce it. +14. **Never `stopService()` a foreground start that may still be pending.** The + service's `onCreate`/`onStartCommand` run on the main thread, so a + `stopService()` issued straight after `startForegroundService()` (a scan that + finished at once, a Cancel tap, a stop from a `Dispatchers.Default` coroutine) + can win the race. The service then never calls `startForeground()` and Android + throws `RemoteServiceException$ForegroundServiceDidNotStartInTimeException` on + the app's main thread ~5–10 s later, with no app frames in the stack. + `ScanService` therefore enters the foreground in `onCreate()` and stops itself + from its own state collector; `ScanServiceTest` pins both halves down. ## 12. Definition of done diff --git a/CHANGELOG.md b/CHANGELOG.md index 92c518e..e124bd7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,27 @@ upload needs a **higher `versionCode`** than every previous upload. ## [Unreleased] +## [1.1.2] — 2026-11-09 · versionCode 7 + +### Fixed + +- **`ForegroundServiceDidNotStartInTimeException` when a scan starts or cancels + quickly.** `ScanController` called `stopService()` from a background coroutine + immediately after `startForegroundService()` (a scan that finished at once, or a + Cancel tap). When that stop beat the pending foreground start, `ScanService` never + ran `startForeground()` and Android killed the process a few seconds later with + `RemoteServiceException$ForegroundServiceDidNotStartInTimeException` — a stack with + no app frames. The service now enters the foreground in `onCreate()` *and* at the + top of every `onStartCommand()` (before the Cancel early-return), tolerates a + `startForeground()` that the system refuses instead of crashing, and stops itself + once `ScanState.scanning` goes false; nothing outside it calls `stopService()` + anymore. Covered by the new Robolectric `ScanServiceTest`. + +### Changed + +- **`versionName` 1.1.2 / `versionCode` 7.** `versionCode` 6 (1.1.1) is already on a + Play track, so the fix needs a new code. + ## [1.1.1] — 2026-10-20 · versionCode 6 ### Fixed diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 20019a5..41175e9 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -89,8 +89,8 @@ android { applicationId = "de.softwareapp_hb.fotodup.finder.free" minSdk = 26 targetSdk = 36 - versionCode = 6 - versionName = "1.1.1" + versionCode = 7 + versionName = "1.1.2" // AdMob reads its application id from the manifest, so it has to be a placeholder: // the value differs between a developer machine, CI and a release build. diff --git a/app/src/main/java/de/softwareapp_hb/fotodup/finder/domain/ScanController.kt b/app/src/main/java/de/softwareapp_hb/fotodup/finder/domain/ScanController.kt index 31c5eaa..7a26efa 100644 --- a/app/src/main/java/de/softwareapp_hb/fotodup/finder/domain/ScanController.kt +++ b/app/src/main/java/de/softwareapp_hb/fotodup/finder/domain/ScanController.kt @@ -91,7 +91,11 @@ class ScanController(context: Context) { if (current.scanning) current.copy(scanning = false, phase = null) else current } job = null - ScanService.stop(appContext) + // ScanService watches this state and stops itself once nothing is running. + // It is deliberately not stopped from here: a stopService() that lands + // while the foreground start is still pending on the main thread means the + // service never calls startForeground(), and the system then kills the app + // with ForegroundServiceDidNotStartInTimeException. } } } @@ -100,7 +104,7 @@ class ScanController(context: Context) { job?.cancel() job = null _state.update { it.copy(scanning = false, phase = null) } - ScanService.stop(appContext) + // As in start(): the service stops itself, see the comment there. } private fun onProgress(progress: ScanProgress) { diff --git a/app/src/main/java/de/softwareapp_hb/fotodup/finder/service/ScanService.kt b/app/src/main/java/de/softwareapp_hb/fotodup/finder/service/ScanService.kt index 4eb651d..312c064 100644 --- a/app/src/main/java/de/softwareapp_hb/fotodup/finder/service/ScanService.kt +++ b/app/src/main/java/de/softwareapp_hb/fotodup/finder/service/ScanService.kt @@ -9,11 +9,13 @@ import android.content.Context import android.content.Intent import android.content.pm.ServiceInfo import android.os.IBinder +import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.app.ServiceCompat import de.softwareapp_hb.fotodup.finder.FotoDupApplication import de.softwareapp_hb.fotodup.finder.MainActivity import de.softwareapp_hb.fotodup.finder.R +import de.softwareapp_hb.fotodup.finder.domain.ScanController import de.softwareapp_hb.fotodup.finder.domain.ScanState import de.softwareapp_hb.fotodup.finder.text.labelRes import kotlinx.coroutines.CoroutineScope @@ -31,24 +33,43 @@ import kotlinx.coroutines.launch * ongoing notification. The notification is also how the user cancels a long scan, and * its presence is what stops Android from freezing the app's process when the app is not * visible. + * + * ### The foreground contract + * + * A service started with `startForegroundService()` must call `startForeground()` within a + * few seconds, otherwise the system throws + * `RemoteServiceException.ForegroundServiceDidNotStartInTimeException`. That is why + * [enterForeground] runs in [onCreate] *and* at the top of every [onStartCommand], before + * any early return: a start that is cancelled or stopped straight away still has to honour + * the contract. For the same reason the service is never stopped from outside with + * `stopService()` — an external stop can land while the start is still pending and then the + * service never gets to call `startForeground()` at all. It stops *itself* as soon as it + * observes that no scan is running. */ class ScanService : Service() { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private var observer: Job? = null + /** The scan owner; always present, the application creates it in `onCreate()`. */ + private val controller: ScanController + get() = (application as FotoDupApplication).scanController + override fun onBind(intent: Intent?): IBinder? = null override fun onCreate() { super.onCreate() createChannel() + // Enter the foreground as early as the framework allows: the system's timer starts + // when startForegroundService() is called, and onCreate() always runs before + // onStartCommand(). Doing it here means even a start that is never handled (because + // the scan finished first) still satisfies the contract. + enterForeground(controller.state.value) } - // The service-type constant is inlined at compile time, so referencing it on older - // devices is harmless — ServiceCompat ignores the type below API 29. - @Suppress("InlinedApi") override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { - val controller = (application as FotoDupApplication).scanController + // First thing on every start, including the ones that stop again immediately. + val inForeground = enterForeground(controller.state.value) if (intent?.action == ACTION_CANCEL) { controller.cancel() @@ -56,26 +77,14 @@ class ScanService : Service() { return START_NOT_STICKY } - // This must happen within a few seconds of startForegroundService(), so it is - // the very first thing we do. - ServiceCompat.startForeground( - this, - NOTIFICATION_ID, - buildNotification(controller.state.value), - ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC, - ) - - if (observer == null) { - observer = scope.launch { - controller.state.collect { state -> - if (state.scanning) { - notifyProgress(state) - } else { - stopEverything() - } - } - } + if (!inForeground || !controller.state.value.scanning) { + // Nothing will ever need this service again (stale notification, a scan that + // already finished). startForeground() above has been satisfied already. + stopEverything() + return START_NOT_STICKY } + + observe() return START_NOT_STICKY } @@ -84,7 +93,7 @@ class ScanService : Service() { * 24). If that ever fires, stop cleanly rather than let the system kill the app. */ override fun onTimeout(startId: Int, fgsType: Int) { - (application as FotoDupApplication).scanController.cancel() + controller.cancel() stopEverything() } @@ -94,14 +103,76 @@ class ScanService : Service() { super.onDestroy() } + /** + * Posts the progress notification and tells the system this is a foreground service. + * + * Must happen within a few seconds of `startForegroundService()`, so callers invoke it + * before doing anything else. A failure only costs the foreground guarantee — the scan + * itself keeps running — so nothing is allowed to escape into the main thread. + * + * @return true when the service really is in the foreground. + */ + // ForegroundServiceStartNotAllowedException (app slipped into the background before the + // service ran), SecurityException (service type or permission missing) and + // MissingForegroundServiceTypeException (API 34+) are all RuntimeExceptions, and a + // throwing notification builder is just as fatal. Catching the whole family is + // deliberate here: a crash on this path is exactly what we are fixing. + @Suppress("TooGenericExceptionCaught", "InlinedApi") + private fun enterForeground(state: ScanState): Boolean { + val notification = try { + buildNotification(state) + } catch (e: RuntimeException) { + Log.w(TAG, "Could not build the scan notification", e) + return false + } + return try { + // The service-type constant is inlined at compile time, so referencing it on + // older devices is harmless: ServiceCompat ignores the type below API 29. + ServiceCompat.startForeground( + this, + NOTIFICATION_ID, + notification, + ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC, + ) + true + } catch (e: RuntimeException) { + Log.w(TAG, "Could not enter the foreground", e) + false + } + } + + /** Mirrors the controller's progress into the notification until the scan is over. */ + private fun observe() { + if (observer != null) return + observer = scope.launch { + controller.state.collect { state -> + if (state.scanning) { + notifyProgress(state) + } else { + // Re-read the newest state: a late emission must not stop a scan that + // was started while this one was in flight. + if (!controller.state.value.scanning) stopEverything() + } + } + } + } + private fun stopEverything() { + observer = null ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE) stopSelf() } private fun notifyProgress(state: ScanState) { - getSystemService(NotificationManager::class.java) - ?.notify(NOTIFICATION_ID, buildNotification(state)) + // A rejected notification must not kill this collector: it is also what stops the + // service, so the scan matters more than the progress bar. Same rationale (and same + // exception family) as enterForeground(). + try { + getSystemService(NotificationManager::class.java) + ?.notify(NOTIFICATION_ID, buildNotification(state)) + } catch (e: RuntimeException) { + Log.w(TAG, "Could not update the scan notification", e) + } } private fun buildNotification(state: ScanState): Notification { @@ -157,15 +228,25 @@ class ScanService : Service() { } companion object { + private const val TAG = "FotoDupScanService" private const val CHANNEL_ID = "scan_progress" private const val NOTIFICATION_ID = 1 private const val PROGRESS_MAX = 100 - private const val ACTION_CANCEL = "de.softwareapp_hb.fotodup.finder.action.CANCEL_SCAN" + + /** Action of the notification's Cancel button; also handled as a direct start. */ + internal const val ACTION_CANCEL = "de.softwareapp_hb.fotodup.finder.action.CANCEL_SCAN" /** * Asks the system to run the service. Safe to call from the background: if the * start is not permitted the exception is swallowed, because the scan itself does * not depend on the service — it only loses the foreground guarantee. + * + * There is deliberately no counterpart that stops the service from here. The + * service stops itself as soon as [de.softwareapp_hb.fotodup.finder.domain.ScanController] + * reports that no scan is running, because an external `stopService()` can arrive + * while this foreground start is still pending on the main thread — and then + * `startForeground()` is never called, which is what the system punishes with + * `ForegroundServiceDidNotStartInTimeException`. */ fun start(context: Context) { try { @@ -174,9 +255,5 @@ class ScanService : Service() { // e.g. ForegroundServiceStartNotAllowedException on Android 12+. } } - - fun stop(context: Context) { - context.stopService(Intent(context, ScanService::class.java)) - } } } diff --git a/app/src/test/java/de/softwareapp_hb/fotodup/finder/service/ScanServiceTest.kt b/app/src/test/java/de/softwareapp_hb/fotodup/finder/service/ScanServiceTest.kt new file mode 100644 index 0000000..05ab9cf --- /dev/null +++ b/app/src/test/java/de/softwareapp_hb/fotodup/finder/service/ScanServiceTest.kt @@ -0,0 +1,108 @@ +package de.softwareapp_hb.fotodup.finder.service + +import android.content.Intent +import android.content.pm.ServiceInfo +import de.softwareapp_hb.fotodup.finder.FotoDupApplication +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +/** + * Guards the foreground-service contract of [ScanService]. + * + * `startForegroundService()` obliges the service to call `startForeground()` within a few + * seconds; if it never happens Android kills the app's process with + * `RemoteServiceException.ForegroundServiceDidNotStartInTimeException`. The service used to + * do that only at the top of `onStartCommand()`, after the Cancel early-return, and + * [de.softwareapp_hb.fotodup.finder.domain.ScanController] additionally called + * `stopService()` from a background coroutine — which can beat the pending start and leave + * `startForeground()` un-called entirely. These tests pin the fixed behaviour down. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [36], application = FotoDupApplication::class) +class ScanServiceTest { + + @Test + fun `onCreate enters the foreground before any command arrives`() { + val service = Robolectric.buildService(ScanService::class.java).create().get() + + val shadow = shadowOf(service) + assertNotNull( + "startForeground() must run in onCreate(), or a start that is never handled " + + "leaves the system waiting for it", + shadow.lastForegroundNotification, + ) + assertFalse("the service must still be in the foreground", shadow.isForegroundStopped) + } + + @Test + fun `a start with no running scan calls startForeground and then stops itself`() { + // No scan is in flight, so the service is useless the moment it starts. This is the + // exact path that used to return early without entering the foreground. + val controller = Robolectric.buildService(ScanService::class.java) + .create() + .startCommand(0, 1) + + val shadow = shadowOf(controller.get()) + // The notification itself is gone again once the service stopForeground()s, but the + // recorded id proves startForeground() ran before it stopped. + assertTrue( + "even a start that stops immediately has to satisfy startForegroundService()", + shadow.lastForegroundNotificationId != 0, + ) + assertTrue("the idle service must stop itself", shadow.isStoppedBySelf) + assertTrue("the foreground state must be released", shadow.isForegroundStopped) + assertTrue("the notification must be removed", shadow.notificationShouldRemoved) + } + + @Test + fun `the notification cancel action also satisfies the foreground contract`() { + val app = RuntimeEnvironment.getApplication() as FotoDupApplication + val cancelIntent = Intent(app, ScanService::class.java).setAction(ScanService.ACTION_CANCEL) + + val controller = Robolectric.buildService(ScanService::class.java).create() + val service = controller.get() + service.onStartCommand(cancelIntent, 0, 1) + + val shadow = shadowOf(service) + assertTrue( + "the cancel path must not skip startForeground()", + shadow.lastForegroundNotificationId != 0, + ) + assertTrue("cancelling stops the service", shadow.isStoppedBySelf) + assertFalse("cancelling leaves no scan running", app.scanController.state.value.scanning) + } + + @Test + fun `a failing startForeground stops the service instead of crashing`() { + // e.g. ForegroundServiceStartNotAllowedException when the app slipped into the + // background before the service ran, or a missing dataSync permission. + val controller = Robolectric.buildService(ScanService::class.java) + shadowOf(controller.get()).setThrowInStartForeground(SecurityException("not allowed")) + + controller.create().startCommand(0, 1) + + val shadow = shadowOf(controller.get()) + assertNull("nothing was posted", shadow.lastForegroundNotification) + assertTrue("the service gives up quietly", shadow.isStoppedBySelf) + } + + @Test + fun `the Android 15 dataSync timeout cancels the scan and stops the service`() { + val app = RuntimeEnvironment.getApplication() as FotoDupApplication + val controller = Robolectric.buildService(ScanService::class.java).create() + + controller.get().onTimeout(1, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) + + assertFalse(app.scanController.state.value.scanning) + assertTrue(shadowOf(controller.get()).isStoppedBySelf) + } +} diff --git a/docs/PLAY_RELEASE_CHECKLIST.md b/docs/PLAY_RELEASE_CHECKLIST.md index 1029edd..0df59d0 100644 --- a/docs/PLAY_RELEASE_CHECKLIST.md +++ b/docs/PLAY_RELEASE_CHECKLIST.md @@ -12,15 +12,16 @@ the rest are things you must do in the Play Console / with your own accounts. `namespace` deliberately stay `de.softwareapp_hb.fotodup.finder`, and debug builds append `.debug` → `de.softwareapp_hb.fotodup.finder.free.debug`. - [x] Generate an **upload keystore** (keep it safe; if you lose it you cannot - publish updates) — **[code]** done: `fotodup-upload.jks` in the project root - (git-ignored, `alias upload`), `CN=Hadrian Burkhardt, L=Potsdam, C=DE`. + publish updates) — **[code]** done: `fotodup-upload.jks` in the central keystore + folder `/home/ubuntu/keystore/` (outside the repo, mode `600`, shared with the paid + listing, `alias upload`), `CN=Hadrian Burkhardt, L=Potsdam, C=DE`. - [x] Copy `keystore.properties.example` to `keystore.properties` and fill it in. **[code]** done — the file is in place, and the Gradle build picks it up automatically and signs release builds; without it the release APK stays unsigned. - [ ] Enable **Play App Signing** for the **new** app in the Play Console and upload the certificate of your *upload* key (the same upload key can sign both listings): ```bash - keytool -exportcert -alias upload -keystore fotodup-upload.jks -rfc > upload_cert.pem + keytool -exportcert -alias upload -keystore /home/ubuntu/keystore/fotodup-upload.jks -rfc > upload_cert.pem ``` Upload key fingerprint (SHA-256), to confirm the right key was registered: `AA:8C:3D:6C:D0:55:46:50:48:ED:04:3E:AF:34:2B:66:B4:13:87:C9:E0:DA:29:70:5A:0D:18:47:08:1A:4C:7A`. @@ -30,11 +31,12 @@ the rest are things you must do in the Play Console / with your own accounts. ## 2. Versioning -- [x] Set `versionName` (user-visible) **[code]** — `1.1.1` in `app/build.gradle.kts`. -- [x] `versionCode` **[code]** — currently **6**. It is the counter Play orders uploads by, and +- [x] Set `versionName` (user-visible) **[code]** — `1.1.2` in `app/build.gradle.kts`. +- [x] `versionCode` **[code]** — currently **7**. It is the counter Play orders uploads by, and every later upload must be higher. Codes 1–3 were consumed by 1.0.0–1.0.2, **4** by - the 1.1.0 internal-testing build (which crashed on startup), and **5** by an earlier - 1.1.1 upload, so the corrected freemium build takes **6**. + the 1.1.0 internal-testing build (which crashed on startup), **5** by an earlier + 1.1.1 upload, and **6** by the corrected freemium build that is already on a track, so + this foreground-service fix takes **7**. ## 3. Build the release artefacts @@ -59,6 +61,16 @@ the rest are things you must do in the Play Console / with your own accounts. APK (`sha256 6043ec92…`) / 7,752,264-byte AAB (`sha256 4766ca49…`); `dexdump` confirms the `WorkDatabase_Impl` public no-arg constructor is present. Rebuild and re-measure if the ids or cutoff change. +- [x] **Build and record the 1.1.2 artefacts** (the `ForegroundServiceDidNotStartInTime` + fix; same real ids and cutoff as 1.1.1, so the size moved by the code alone): a + **3,688,330**-byte APK (`sha256 5d43c515…`) and a **7,753,331**-byte AAB + (`sha256 51c83829…`), signed with the upload key from step 1 + (`CN=Hadrian Burkhardt`, SHA-256 `AA:8C:3D:…:1A:4C:7A`) and R8-minified. + `jarsigner -verify` says *jar verified* for the `.aab`; `aapt2 dump badging` + reports package `de.softwareapp_hb.fotodup.finder.free`, + `versionCode=7 versionName=1.1.2 targetSdk=36`; the merged release manifest + contains no AdMob test id. Rebuild and re-measure after any code, id or cutoff + change. - [ ] **Launch the minified build before uploading.** Do not rely on `assembleDebug`/unit tests: they do not run R8. Install the release APK on a real device (or a temporarily minified debug build side by side) and confirm it @@ -100,9 +112,15 @@ action except the items marked **[code]**. 2. *Monetise > Products > In-app products* → create **`pro_no_ads`**, type **One-time product**, set the price, **Activate** it. The product id must match `ProProduct.ID` exactly; an inactive product is not returned by Play. - 3. AdMob → create/link the Android app, one **Banner** unit and a **UMP message**. - Put the ids in `local.properties` (`admob.appId`, `admob.bannerUnitId`) or pass - `-Padmob.appId=...`; never commit them. + 3. AdMob → link the Android app (`…finder.free`), create one **Banner** unit, and + **publish** a UMP message under *Privacy & messaging* (the European-regulations + message that *Maximize message coverage* auto-creates is fine once it is + published, not a draft). Put the ids in `local.properties` (`admob.appId`, + `admob.bannerUnitId`) or pass `-Padmob.appId=...`; never commit them. Host + `app-ads.txt` at the root of the developer website listed on the Play listing. + App verification is followed by a separate AdMob ad-serving review (2–3 days, + sometimes longer) with **limited serving** until it clears: an empty banner in + that window is expected, not a code defect. 4. Set `legacyPro.cutoffEpochMs` to the instant of the first freemium release. Installs older than that are grandfathered into Pro; a `0` cutoff disables the migration. Because the new app has a different applicationId, this only works @@ -462,7 +480,11 @@ action except the items marked **[code]**. virtual instruction counter dilates the guest clock and made it work exactly once (`-qemu -icount shift=1,sleep=off`, guest clock measured 2.30× slow) but not reproducibly, so that is a lead rather than a recipe; `SETTLE_SECONDS` / `WARM_SECONDS` - scale this script's waits if it is ever retried. + scale this script's waits if it is ever retried. Note that part of that crash was a real + app bug (see pitfall 14 in `AGENTS.md`): a scan that reports idle straight away used to + let `stopService()` beat the pending foreground start, so `startForeground()` was never + called. Since the fix, that specific race no longer occurs and `ScanServiceTest` covers + it, but the emulator remains too slow to prove a *device* recording. The declaration is **per type**: if a new foreground-service type is ever added to the manifest, it has to be declared here too. @@ -538,7 +560,9 @@ action except the items marked **[code]**. ## 7. Release notes ("What's new") and rollout ⚠️ **Which block applies:** the freemium app is a **new `.free` listing**, so its first -release uses the “new freemium listing” block below. The 1.0.2 and initial-release +release uses the “new freemium listing” block below. **The current upload is the 1.1.2 +update, so use the 1.1.2 block** (its notes belong to that release; the first-release +block stays here for the listing's initial submission). The 1.0.2 and initial-release blocks are kept for the history of the old paid listing; the old initial block still says “no ads”, which was true only of the paid build. The 1.1.0-update block has been replaced because the plan is a new listing, not an in-place price change. @@ -565,6 +589,25 @@ Rules (per Google's *Prepare and roll out a release* guide): - For app updates list only user-visible changes; the full developer history belongs in [CHANGELOG.md](../CHANGELOG.md). +Ready-to-paste block for the **1.1.2 update** (`versionCode` 7) — the foreground-service +fix (223 chars): + + + Fixed a crash that could happen right after starting or cancelling a scan. + + • The scan notification now appears immediately, so a running scan keeps going while you use other apps + • Cancelling a scan no longer stops the app + + +Optional German block for the same update (252 chars): + + + Ein Absturz direkt nach dem Starten oder Abbrechen eines Scans ist behoben. + + • Die Scan-Benachrichtigung erscheint jetzt sofort, damit ein laufender Scan weiterläuft, während du andere Apps benutzt + • Das Abbrechen eines Scans beendet die App nicht mehr + + Ready-to-paste block for the **new freemium listing's first release** (313 chars): diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 4be45f0..d59fdb3 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -48,9 +48,10 @@ Legend: ✅ done · 🚧 in progress · ⏳ not started · 💡 candidate (propo ## Suggested order 1. ✅ **Done** — the scan-stall hardening and the `BoundedCall` fix shipped as **1.0.1** - (`versionCode` 2); **1.0.2** (`versionCode` 3) was the last paid build. The next upload is - **1.1.1** (`versionCode` 6), the fixed freemium build, which also needs the Play Console changes in - [MONETIZATION](MONETIZATION.md). Only the on-device re-check of the 5,363-photo scan remains. + (`versionCode` 2); **1.0.2** (`versionCode` 3) was the last paid build. The freemium + listing went out as **1.1.1** (`versionCode` 6); the current upload is **1.1.2** + (`versionCode` 7), the `ForegroundServiceDidNotStartInTime` fix, which still needs the + Play Console changes in [MONETIZATION](MONETIZATION.md). 2. Finish the Play Console paperwork and roll out through **internal → closed → production**. 3. ✅ **Done** — **M10 store assets**: the icon and feature graphic are generated from the app's own vectors, the screenshot normaliser enforces Play's 2:1 limit, the listing copy is diff --git a/docs/codemap.md b/docs/codemap.md index dc17274..7c56f84 100644 --- a/docs/codemap.md +++ b/docs/codemap.md @@ -178,7 +178,7 @@ sequenceDiagram SE-->>SC: ScanProgress.Finished(ScanResult) SC-->>VM: StateFlow VM-->>UI: groups, summary, selection - SC->>SVC: stop foreground service + SVC->>SVC: sees "not scanning" and stops itself ``` ### Phases @@ -196,6 +196,16 @@ keeps going when the app is backgrounded because `ScanService` holds a `dataSync foreground service for the duration. The ViewModel only mirrors progress; it never owns the scan. +`ScanService` enters the foreground in `onCreate()` *and* at the top of every +`onStartCommand()`, before any early return. `startForegroundService()` obliges the +service to call `startForeground()` within a few seconds, and a start that is +cancelled (notification Cancel, in-app Cancel) or already finished is still a start. +For the same reason nothing outside the service calls `stopService()`: an external +stop can land while the start is still queued on the main thread, which leaves +`startForeground()` un-called and surfaces as +`RemoteServiceException.ForegroundServiceDidNotStartInTimeException`. The service +stops itself as soon as it observes `ScanState.scanning == false`. + Three failure boundaries matter: - `BoundedCall` gives every provider call a deadline, so one wedged file cannot @@ -472,7 +482,9 @@ Paths are relative to `app/src/main/java/de/softwareapp_hb/fotodup/finder/` unle `BannerAdSlot` owns the `AdView` lifecycle and requests exactly one banner. - **MediaDeleter** owns the system consent request. No other class may delete a photo or bypass the two-step staging flow. -- **ScanService** mirrors `ScanController`; it contains no scanning logic. +- **ScanService** mirrors `ScanController`; it contains no scanning logic. It owns the + foreground contract (enter the foreground in `onCreate`, stop itself when idle) and + is never stopped from outside. - **core/** stays pure Kotlin. A new Android import there is an architecture bug. ## 11. Keeping the map accurate