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.
This commit is contained in:
2026-11-09 00:25:56 +01:00
parent 4739069737
commit 6d031082a3
9 changed files with 336 additions and 57 deletions
+2 -2
View File
@@ -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.
@@ -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) {
@@ -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))
}
}
}
@@ -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)
}
}