0

I have started a service like this:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    context.startForegroundService(intent);
} else {
    context.startService(intent);
}

But when I want to stop this service then I faced an error which is:

android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6501)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

To resolve this error I tried: 1.Used stopSelf(); in onDestroy() method. 2. Used startForeground(0, new Notification()); in the onCreate() method.

But the error still remains. I searched a lot on StackOverflow and android official websites also. Can't find any suitable answer to solve my problem. By the way, this error starts from Android OREO version.

Ali Ahmed
  • 1,159
  • 1
  • 8
  • 18

1 Answers1

0

As mentioned here

"Android 8.0 introduces the new method startForegroundService() to start a new service in the foreground. After the system has created the service, the app has five seconds to call the service's startForeground() method to show the new service's user-visible notification. If the app does not call startForeground() within the time limit, the system stops the service and declares the app to be ANR."

Murtadha S.
  • 442
  • 6
  • 15