Skip to content

Android: ForegroundServiceDidNotStartInTimeException during rapid foreground/background transitions #203

Description

@Jianlong-Nie

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.

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)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions