I am getting an error that does not make sense to me
The error I get is
RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
I have a BroadcastReceiver that gets fore from an exact alarm and that receiver starts a service to do some short work
override fun onReceive(context: Context, intent: Intent) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
context.startForegroundService(Intent(context, RestartService::class.java))
}else{
context.startService(Intent(context, RestartService::class.java))
}
}
then in my service class I make sure to start foreground
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create a new notification channel
val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
// Create a notification
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(title)
.setContentText(content)
.setSmallIcon(R.mipmap.app)
.build()
// Start the service in the foreground
startForeground(NOTIFICATION_ID, notification)
return START_NOT_STICKY
}
as you can see I am calling startForeground
in my onStartCommand
I know about the background restrictions but for testing I have enabled my app to Draw over other apps
which the documentation says would allow me to start a service and an activity when the app is in the background as well as having this come from an exact alarm. This error happens when app is in the foreground too
I dont know what I am missing here
It looks like my code in onCreate
was completing too fast and the service was unable to call startForeground
before I was stopping the service causing the exception