首页 > 解决方案 > context.startForegroundService(startServiceIntent) 多次会调用 onCreate 多次?

问题描述

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

标签: androidservice

解决方案


这取决于服务是否正在运行。如果该服务尚未运行,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

推荐阅读