aws / aws/amazon-ivs-react-native-player
Android: ForegroundServiceDidNotStartInTimeException during rapid foreground/background transitions
- Dominant language
- TypeScript
- Stars
- 313
- Forks
- 42
- PR merge metrics
- No merged PRs in 30d
Description
## Description
`IVSBackgroundService` crashes with `ForegroundServiceDidNotStartInTimeException` on Android when the app undergoes a rapid foreground/background transition while the IVS player is active.
## Error
```
android.app.RemoteServiceException$ForegroundServiceDidNotStartInTimeException:
Context.startForegroundService() did not then call Service.startForeground():
ServiceRecord{... com.amazonaws.ivs.reactnative.player.IVSBackgroundService}
```
## Root Cause
In `IVSBackgroundService.onStartCommand()`, `startForeground()` is called after `createNotificationChannel()`. Android requires `startForeground()` to be called within 5 seconds of `startForegroundService()`. Under memory pressure or when service startup is delayed by rapid app lifecycle transitions, this window can be exceeded before `onStartCommand()` is ever reached.
## Suggested Fix
Move `createNotificationChannel()` and `startForeground()` to `onCreate()`, which is invoked immediately when the service is created — before `onStartCommand()` — ensuring the foreground declaration happens as early as possible.
```kotlin
override fun onCreate() {
super.onCreate()
createNotificationChannel()
startForeground(NOTIFICATION_ID, buildNotification(true, "", ""))
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val action = intent?.action
when (action) {
ACTION_STOP -> {
stopForeground(true)
stopSelf()
return START_NOT_STICKY
}
// ...
}
val isPlaying = intent?.getBooleanExtra(EXTRA_IS_PLAYING, true) ?: true
val notificationTitle = intent?.getStringExtra(NOTIFICATION_TITLE) ?: ""
val notificationText = intent?.getStringExtra(NOTIFICATION_TEXT) ?: ""
// Update notification content — channel already created in onCreate()
startForeground(NOTIFICATION_ID, buildNotification(isPlaying, notificationTitle, notificationText))
return START_NOT_STICKY
}
```
## Environment
- `amazon-ivs-react-native-player`: 1.6.0
- Android 12+
- Reproducible under low memory conditions with quick background/foreground transitions (observed with a 37ms pause/resume cycle)
Contributor guide
Research direction
Locate IVSBackgroundService and inspect its onCreate() and onStartCommand() lifecycle. Reproduce rapid foreground/background transitions on Android 12+ under low-memory conditions, then verify the service enters the foreground within the startup window without ForegroundServiceDidNotStartInTimeException and that notification updates still work.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- android, kotlin, react-native
- Domain
- mobile
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Quiet
- Clarity
- Clearly specified
- Newbie friendliness
- 65/100