Krishna Sharma
Krishna Sharma

Reputation: 2877

Foreground service issue - did not then call Service.startForeground()

Found an interesting observation with foreground service, if we stop the service immediately right just after start foreground service we get this error as Context.startForegroundService() did not then call Service.startForeground(). Doesn't matter whether we start notification from onCreate or onStartCommand of service.

Intent intent = new Intent(this, MyService.class)
startForegroundService(intent);
stopService(intent);

But if I add a delay then it's working as expected, any thought on this ?

Intent intent = new Intent(this, MyService.class)
startForegroundService(intent);
new Handler(Looper.getMainLooper()).postDelayed(() -> stopService(intent), 0);

In order to get rid of this error this is how I fixed

I didn't found any proper documentation on developer website but this is what I did in order to solve Context.startForegroundService() did not then call Service.startForeground() issue.

If we want to stop foreground service do not call outside the service class using stopService(intent) instead create an intent action, start the foreground service then stop the service using stopSelf from service onStartCommand.

Intent serviceIntent = new Intent(context, MyService.class);
serviceIntent.setAction(ACTION_STOP_SERVICE);
ContextCompat.startForegroundService(context, serviceIntent);

Upvotes: 1

Views: 888

Answers (1)

laalto
laalto

Reputation: 152907

Starting a service is not synchronous and the service is not up and running when the start call returns. Think of it as posting a message to your main thread looper queue that get processed later.

Now your Handler approach is also doing the same kind of thing to postpone the execution - post a runnable to the main thread looper queue. It gets processed after the previous messages in the queue have been processed, so there's some Service startup lifecycle code that has been executed before the stopService() is invoked.

Upvotes: 0

Related Questions