startService() throws java.lang.IllegalStateExcept

2019-06-19 02:59发布

问题:

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.

回答1:

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().