onStartCommand

open override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int

Called when the service is started or restarted. This method manages the foreground state of the service.

It attempts to start the service in the foreground with a notification. If startForeground fails, for example, due to a SecurityException on Android 13+ because the POST_NOTIFICATIONS permission is missing, it logs an error* and returns START_NOT_STICKY to prevent the service from becoming sticky in a broken state.

If the service is not intended to be in the foreground (e.g., no device is connected), it stops the foreground state and returns START_NOT_STICKY. Otherwise, it returns START_STICKY.

Return

The return value indicates what semantics the system should use for the service's current started state. See Service.onStartCommand for details.

Parameters

intent

The Intent supplied to startService(Intent), as modified by the system.

flags

Additional data about this start request.

startId

A unique integer representing this specific request to start.