context.startForegroundService(startServiceIntent) 多次会调用 onCreate 多次?

Baz*_*555 3 service android

如果我多次调用 context.startForegroundService(startServiceIntent),我会多次调用具有新服务意图的 onCreate() 还是第一次调用 onCreate 以获得新的服务意图,然后多次调用 onStartCommand()/onHandleIntent()次?

Com*_*are 7

这取决于服务是否正在运行。如果该服务尚未运行,startForegroundService()将触发调用onCreate()

因此,例如:

  • 你打电话 startForegroundService()
  • Android 创建您的服务实例并调用onCreate()
  • 然后 Android 调用onStartCommand()它(这可能会触发对其他事物的调用,例如onHandleIntent()of IntentService
  • startForegroundService()再打电话
  • Android 意识到您有一个正在运行的服务副本并且不会创建新的副本,因此没有onCreate()调用
  • 然后 Android 调用onStartCommand()它(这可能会触发对其他事物的调用,例如onHandleIntent()of IntentService
  • 您停止服务,通过类似stopService()stopSelf()(或onHandleIntent()返回,如果您仍在使用IntentService
  • startForegroundService()再次打电话,因为你真的很喜欢那个方法
  • Android 创建您的服务实例并调用onCreate()
  • 然后 Android 调用onStartCommand()它(这可能会触发对其他事物的调用,例如onHandleIntent()of IntentService