Bazouk55555
Bazouk55555

Reputation: 567

context.startForegroundService(startServiceIntent) multiple time will call onCreate multiple times?

If I call context.startForegroundService(startServiceIntent) multiple time, will I call onCreate() with a new service intent multiple times or I will I call the first time onCreate for a new service intent and then call onStartCommand()/onHandleIntent() multiple times?

Upvotes: 3

Views: 1447

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006819

It depends if the service is running or not. startForegroundService() will trigger a call to onCreate() if that service is not already running.

So, for example:

  • You call startForegroundService()
  • Android creates an instance of your service and calls onCreate() on it
  • Android then calls onStartCommand() on it (which may trigger calls to other things, like onHandleIntent() of IntentService)
  • You call startForegroundService() again
  • Android realizes that you have a running copy of the service and does not create a new one, so there is no onCreate() call
  • Android then calls onStartCommand() on it (which may trigger calls to other things, like onHandleIntent() of IntentService)
  • You stop your service, via something like stopService() or stopSelf() (or onHandleIntent() returns, if you are still using IntentService)
  • You call startForegroundService() again, because you really like that method
  • Android creates an instance of your service and calls onCreate() on it
  • Android then calls onStartCommand() on it (which may trigger calls to other things, like onHandleIntent() of IntentService)

Upvotes: 11

Related Questions