Context.startForegroundService() Did Not Then Call Service.startForeground(): Solved

Saurabh Vashisht
Geek Culture
Published in
2 min readMay 22, 2021

--

For the past year or so, this issue had been a constant companion of mine. The reason for this crash is

“From Android 9 Pie if your service does not call startForeground within 5 seconds after it has been started with the command startForegroundService ... then it produces an ANR + Crash.”

No matter what I did including

  1. Adding a startForeground() command, with notification, right at the beginning of the onStartCommand method of foreground service.
  2. Adding startForeground() command, with notification in the onCreate method.

It didn’t work. Also, the issue couldn’t be reproduced during testing which makes it all the more difficult to fix.
Before we begin discussing the solution let’s look at what happens when we start a foreground service.

Service start flow chart

This is what you would do if you have just read the developer docs here.

Before we start discussing the solution, you must be aware of what a bound service is. Read about bound services here
https://developer.android.com/guide/components/bound-services

So let’s talk about the solution:

Instead of starting the service as a foreground service, start the service as a background service, bind to it, then when you have the service instance available in your activity/UI component, you can directly call a method inside the service. At this point, you can call

Intent intent = new Intent(context, MyService.class);
ContextCompat.startForegroundService(context, intent);
mService.doForegroundThings();

Add a method doForeGroundThings() in your service class and add the foreground notification in this method.
That’s it. Now you have your foreground service with a notification.
If you are interested in looking at code, you can check out this sample application code

--

--