For Foreground Services it's not important from which callback of Activity you start them, because they can work even if app is working background.
You can get IllegalStateException
if you start Foreground Service without calling startForeground
method. Make sure the code of your Service contains code similar to the following:
class ExampleService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// prepare pending intent
val pendingIntent = val pendingIntent: PendingIntent =
Intent(this, ExampleActivity::class.java).let { notificationIntent ->
PendingIntent.getActivity(this, 0, notificationIntent, 0)
}
// build notification to display while foreground service is running
val notification =
NotificationCompat.Builder(context, "channel_id")
.setContentTitle("Title")
.setContentText("Text")
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.small_icon)
.build()
val notificationId = 42
// call tell the system run your service as foreground service
startForeground(notificationId, notification)
// implement the business logic
....
}
}
You can find more info about Foreground Services here: https://developer.android.com/guide/components/foreground-services