9

From onCreate() of my Activity,

I am trying to start a service via following code:

Intent intent = new Intent();
intent.setClassName(SERVICE_PKG_NAME, SERVICE_NAME);
context.startService(intent); //context = MainActivity.this

However, I receive following exception:

java.lang.IllegalStateException: Not allowed to start service Intent (service-name) : app is in background

Any idea what could be reason for this? Stuck on it for few hours now.

13
  • 1
    What version of Android are you testing on? Also, can you post the entire Java stack trace? Commented Jun 1, 2017 at 14:23
  • 2
    @CommonsWare Android -O. From developer.android.com/preview/behavior-changes.html seems newly added. bold The startService() method now throws an IllegalStateException if an app targeting Android O tries to use that method in a situation when it isn't permitted to create background services.**bold** Commented Jun 2, 2017 at 4:13
  • 1
    Your error message matched what I was seeing from O, which is why I was asking about the device version. Where and when are you trying to start the service? Commented Jun 2, 2017 at 10:32
  • 1
    "so system won't allow to start Service for app in Background" -- that does not make any sense. App A is in the foreground. It is supposed to be able to start services to its heart's content, including any services of App B. Regardless, try binding to the service first, then calling startService() for that same service once the service is bound. Commented Jun 2, 2017 at 12:28
  • 1
    Perhaps A, B, and C should all be one app. Regardless, you can try calling startForegroundService() on Context instead of startService(). Commented Jul 17, 2017 at 11:06

1 Answer 1

3

For cases involving need to invoke service of Background app from a foreground app, We can follow the sequence:

  • call bindService() first
  • after OnServiceConnected() due to bind call
  • call StartService().
Sign up to request clarification or add additional context in comments.

5 Comments

So this has to be a Bound Service?
So how do I start a service in reaction to a Firebase Notification?
@DanielF I think it's better to use JobScheduler for it. You can specify the Job to be started to it, based on certain condition like Charger Connected etc. developer.android.com/reference/android/app/job/…
@SahilMehta Thanks for your feedback. My issue was that I started targeting API 26 and there you can't invoke a service from the background unless you do it with startForegroundService (I think that was the name), You have to pass it a notification then.
@DanielF ,I think JobScheduler should help in this case. I had a similar scenario.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.