First of all, I looked at these;
The Android Service
component is a bit tricky to get working properly, especially on later Android versions where the OS adds additional restrictions. As mentioned in other answers, when starting your Service
, use ContextCompat.startForegroundService()
. Next, in Service.onStartCommand()
, call startForeground()
immediately. Store the Notification
you want to show as a member field and use that unless it is null. Example:
private var notification:Notification? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (notification == null) {
notification = createDefaultNotification()
}
startForeground(NOTIFICATION_ID, notification)
// Do any additional setup and work herre
return START_STICKY
}
Always return START_STICKY
in your Service
. Anything else is probably the wrong thing, especially if you're doing a audio player of any kind. In fact, if you're doing an audio player, you shouldn't implement your own Service but use MediaBrowserServiceCompat (from AndroidX) instead.
I also recommend the blog posts I wrote on this: https://hellsoft.se/how-to-service-on-android-part-3-1e24113152cd