startService()抛出java.lang.IllegalStateException

Sah*_*hta 7 android android-service android-8.0-oreo

onCreate()我的活动,

我试图通过以下代码启动服务:

Intent intent = new Intent();
intent.setClassName(SERVICE_PKG_NAME, SERVICE_NAME);
context.startService(intent); //context = MainActivity.this
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下异常:

java.lang.IllegalStateException:不允许启动服务Intent(service-name):app在后台

知道这可能是什么原因吗?现在坚持几个小时.

Sah*_*hta 3

对于需要从前台应用程序调用后台应用程序服务的情况,我们可以遵循以下顺序:

  • 首先调用bindService()
  • 由于绑定调用而导致 OnServiceConnected() 之后
  • 调用StartService()。