Skip to content

Fix: Improve background service crash recovery#555

Merged
d4rken merged 1 commit into
mainfrom
fix/foreground-handler-safety
Apr 25, 2026
Merged

Fix: Improve background service crash recovery#555
d4rken merged 1 commit into
mainfrom
fix/foreground-handler-safety

Conversation

@d4rken

@d4rken d4rken commented Apr 25, 2026

Copy link
Copy Markdown
Member

What changed

Makes the existing safety net for the rare ForegroundServiceDidNotStartInTimeException cold-start crash more robust against edge cases. No visible difference in normal use — only matters when the safety net itself runs.

Technical Context

  • The suppression handler in App.kt (added in 29df9062) uses Looper.loop() to keep the main thread alive after swallowing one occurrence of the timing exception. Three latent issues are fixed here.
  • Looper.loop() was called regardless of which thread the throwable arrived on. The default uncaught handler can run on non-main threads, where Looper.loop() itself would throw. Now guarded by thread === Looper.getMainLooper().thread.
  • The var foregroundExceptionHandled flag was a captured local with no synchronization. Replaced with AtomicBoolean.compareAndSet(false, true) so two concurrent throws can't both reach the suppression branch.
  • A failure inside the in-handler log(...) or Bugs.report(...) calls would escape and become its own uncaught exception. Both calls are now wrapped in runCatching {}.
  • Considered and rejected: hoisting the handler install above super.onCreate(), and pre-creating the notification channel in MonitorControl before startForegroundService(). The cold-start trace shows Application.onCreate() completes before manifest receivers fire, so the handler is already installed before the 5-second timer can run out; channel creation is idempotent across app starts so pre-creating outside MonitorService.onCreate() only helps first install.

@d4rken d4rken added the bug Something isn't working label Apr 25, 2026
@d4rken d4rken merged commit f67e8aa into main Apr 25, 2026
10 checks passed
@d4rken d4rken deleted the fix/foreground-handler-safety branch April 25, 2026 21:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant