Skip to content

fix: stop the android background service behind its pending start - #211

Closed
tngo-intern wants to merge 1 commit into
aws:mainfrom
tngo-intern:fix/android-background-service-stop
Closed

tngo-intern wants to merge 1 commit into
aws:mainfrom
tngo-intern:fix/android-background-service-stop

Conversation

@tngo-intern

Copy link
Copy Markdown

Issue #, if available: #203

Description of changes:

startBackgroundService() calls ContextCompat.startForegroundService(), and stopBackgroundService() calls context.stopService(). When the app goes to the background and comes straight back, the stop can arrive before the service's onStartCommand() has called startForeground(). Android 12+ then crashes the app with ForegroundServiceDidNotStartInTimeException.

This change stops the service by sending its existing ACTION_STOP intent with startService(), instead of calling stopService(). Start commands are delivered in order, so onStartCommand() for the pending start, and its startForeground() call, always run before the stop. It also skips the stop when this view never started the service. If the app is not allowed to start services at that moment, it falls back to stopService().

We carry this as a local patch on 1.6.0 in a production app, with no change to background playback.

#203 suggests calling startForeground() from onCreate(). That would also help, and the two changes fit together. Happy to add it here if you prefer.

Testing: the change is Kotlin only. I have not run it in this repository's example app.

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

🤖 Generated with Claude Code

stopBackgroundService() called context.stopService() directly. When the app
went to the background and straight back, the stop could arrive before the
service's onStartCommand() had called startForeground(), and Android 12+
crashed the app with ForegroundServiceDidNotStartInTimeException.

Send the service's ACTION_STOP intent with startService() instead. Start
commands are delivered in order, so startForeground() always runs first.
Skip the stop when this view never started the service, and fall back to
stopService() when the app may not start services.

Fixes aws#203

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tngo-intern

Copy link
Copy Markdown
Author

Closing this; we're keeping the fix in our own project for now. Sorry for the noise.

@tngo-intern tngo-intern closed this Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants