Skip to content

fix: Call startForeground() before Hilt DI to prevent timing crash#388

Merged
d4rken merged 1 commit intomainfrom
fix/foreground-service-timing
Feb 13, 2026
Merged

fix: Call startForeground() before Hilt DI to prevent timing crash#388
d4rken merged 1 commit intomainfrom
fix/foreground-service-timing

Conversation

@d4rken
Copy link
Copy Markdown
Member

@d4rken d4rken commented Feb 13, 2026

Summary

  • Call startForeground() with a minimal notification BEFORE super.onCreate() (which triggers Hilt DI) to prevent ForegroundServiceDidNotStartInTimeException on cold background starts
  • After DI completes, replace the early notification with the full one via a second startForeground() call
  • Deduplicate notification channel creation by having the init block delegate to the new static ensureChannel() helper
  • Extract PENDING_INTENT_REQUEST_CODE constant to make PendingIntent coupling explicit

Context

When BluetoothEventReceiver fires in the background (e.g., AirPods connect while phone is in pocket), MonitorService.onCreate() calls super.onCreate() which triggers Hilt DI for 12 injected fields. The DI chain includes SharedPreferences disk I/O, layout inflation, Moshi reflection, and system service lookups that can exceed the ~5s foreground service timeout on production devices with cold caches.

Test plan

  • Build: ./gradlew assembleFossDebug
  • Test Bluetooth ACL connect while app is backgrounded
  • Test device boot via BootCompletedReceiver
  • Test app cold start from launcher
  • Verify notification transitions smoothly from early to full

Move startForeground() before super.onCreate() in MonitorService to
avoid ForegroundServiceDidNotStartInTimeException when Hilt DI is slow
on backgrounded cold starts. An early minimal notification is shown
immediately, then replaced with the full one after DI completes.
@d4rken d4rken added the bug Something isn't working label Feb 13, 2026
@d4rken d4rken merged commit 86d3f3b into main Feb 13, 2026
9 checks passed
@d4rken d4rken deleted the fix/foreground-service-timing branch February 13, 2026 13:39
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