Context.startForegroundService() did not then call Service.startForeground()

from the CommonsWare Community archives

At September 7, 2019, 7:34am, rd7773 asked:

I am starting foreground service from MainActivity’s onCreate like this :

mHandler.post {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                context.startService(Intent(context, MyService::class.java))
            } else {
                context.startForegroundService(Intent(context, MyService::class.java))
            }
        }

Then inside MyService (extends Service) class

override fun onCreate() {

        super.onCreate()

        notificationHelper.createNotificationChannel()

        startForeground(1005, notificationHelper.getNotification(this))
          
    }

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)

        (getSystemService(Context.POWER_SERVICE) as PowerManager).run {
                newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, tag).apply {
                    acquire()
                }
         }

        return START_STICKY
    }

override fun onDestroy() {
        super.onDestroy()
        stopForeground(true)
    }

Everything is working fine on most devices but on few devices running on android 9 (100%), i am getting this error Context.startForegroundService() did not then call Service.startForeground(). Any idea why this might be happening and only on android 9 ?


At September 7, 2019, 11:16am, mmurphy replied:

That’s a known problem. If you search the issue tracker for “did not call startForeground”, you will find a zillion issues. This one is the one that I was keeping an eye on. The working theory is that in some cases there is a delay between the startForegroundService() call and when the service actually starts.

I think this is fixed in Android 10. There are some unpleasant workarounds in that issue that I pointed you to.