Android Oreo brought in some new limitations on background processing. I think the goal of this was to put restrictions on apps that were silently eating away at battery on previous OS versions. While this is good news for consumers, there are some pitfalls to watch out for as a developer when you change your compileSdkVersion to 26 or above. The one particular pitfall I’m writing about in this article is startForegroundService vs startService.

What has changed?

From Oreo(API 26) on-wards you can no longer start a Service when your app is in the background. An example of this is a situation where you are starting a Service from a BroadcastReceiver. If your app is in the foreground startService will still work as expected, but if it’s not in the foreground the system will just stop your Service from starting – which is pretty inconvenient.

How can you get it around it?

If you replace your startService call with a startForegroundService call you can bypass this restriction. There is a catch though, you have to make sure you promote the Service to the foreground within 5 seconds. If you decide to use this method I suggest putting your startForeground call in the onCreate method of your Service. If you are doing anything else make sure it’s after this call because if more than 5 seconds passes the system will just kill your Service.

What if I’m not using a Foreground Service?

If you’re not using a Foreground Service there is another way around these restrictions, you can use a JobIntentService instead. I plan on writing about that in a future article as well. You could also try using Firebase JobDispatcher instead, which is a Google maintained library for scheduling recurring tasks. You can read more about Firebase JobDispatcher here.