22

Is there a way to check that the service is not already running before starting it?

If it could be in the onCreate() of the service it will be even better,

Thank you!

3 Answers 3

36

You can't start a service twice, it will remain running if you try to start it again. Link to the Android docs.

4
  • 1
    it must be due to something else which causes the crash
    – waqaslam
    Mar 8, 2012 at 23:19
  • Per docs: "Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called;" developer.android.com/reference/android/app/…
    – Tazzy531
    Nov 30, 2013 at 22:38
  • So if I start my service 200 times in a for loop, it will continue to run as if I started it once? Feb 6, 2016 at 21:18
  • @RuchirBaronia Why not test it out?
    – Matt K
    Feb 7, 2016 at 22:35
0

I just tested on Android 9 (API 28) that you can start the same service with the same Intent as many times as you want:

onCreate() {
    startMyService();
    startMyService();
    startMyService();
    startMyService();
    startMyService();
    startMyService();
    startMyService();
    startMyService();
    startMyService();
    startMyService();
}
private void startMyService() {
    Intent serviceIntent = new Intent(this, MyService.class);
    ContextCompat.startForegroundService(this, serviceIntent);
}

One way to avoid this is to stop it before starting it by passing the identical Intent:

private void startMyService() {
    Intent serviceIntent = new Intent(this, MyService.class);
    stopService(serviceIntent); // <<<<< this line makes sure that you don't start it twice or more times
    ContextCompat.startForegroundService(this, serviceIntent);
}
-2

fix it with a boolean/flag in the service. (A service can only be started once)

2
  • 2
    You shouldn't have to do this. It may be indicative of another problem. Are you doing something in the service's onStartCommand() that you should be doing in onCreate() instead?
    – Matt K
    Dec 3, 2013 at 15:53
  • 1
    Nobody can get answer from your answer Mar 17, 2016 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.