title: Starting a foreground service when an app is background restricted on Android Pie
body: <p>With Android 9.0 (Pie), it's possible for the user to restrict your app from doing background work through settings. Our app has seen the following exception when we try to start a foreground service on Pie devices if the app is background restricted even when an app activity is fully in the foreground.</p>
  
  <pre><code>RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
  </code></pre>
  
  <p>We do call startForeground() in the started Service, but the system log when attempting to start the service shows:</p>
  
  <pre><code>system_process W/ActivityManager: Service.startForeground() not allowed due to bg restriction
  </code></pre>
  
  <p>Seems odd to receive an exception when you're following <a href="https://developer.android.com/guide/components/services#Foreground" rel="noreferrer">the documented steps</a> for foreground services, and the system is rejecting the app from starting the foreground service when your app is also in the foreground still. I have yet to find much documentation relating to this, but is this documented behavior? And is there at least a way for your app to know if it's been background restricted and thus not attempt to start the service in the foreground?</p>
  
  <p><a href="https://i.stack.imgur.com/wEIYS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wEIYS.png" alt="enter image description here"></a></p>
  
  <p>My Service code essentially looks like below. Our target api is 27.</p>
  
  <pre><code>class MyService : Service() {
  
      override fun onCreate() {
          super.onCreate()
          // create notification
          startForeground(NOTIFICATION_ID, notification)
      }
  
      override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
          if (intent == null || intent.action == null || intent.action == ACTION_STOP) {
              quit()
          }
          doWork()
          return START_NOT_STICKY
      }
  
      override fun onBind(intent: Intent?): IBinder? {
          return null
      }
  
      override fun onTaskRemoved(rootIntent: Intent?) {
          super.onTaskRemoved(rootIntent)
          quit()
      }
  
      private fun quit() {
          stopForeground(true)
          stopSelf()
      }
  
      companion object {
  
          fun start(context: Context) {
              val intent = Intent(context, MyService::class.java)
              intent.action = ACTION_START
              ContextCompat.startForegroundService(context, intent)
          }
  
          fun stop(context: Context) {
              val intent = Intent(context, MyService::class.java)
              intent.action = ACTION_STOP
              ContextCompat.startForegroundService(context, intent)
          }
      }
  }
  </code></pre>