72

There are some conditions where my service could be attempted to be started when it should not be. In cases like this is it bad form to call stopSelf() while inside a onStartCommand() method? If so what is the best way to handle such a situation? Any resources will be greatly appreciated.

Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147

1 Answers1

91

is it bad form to call stopSelf() while inside a onStartCommand() method?

Off the top of my head, I can't think of why that would be a problem.

stopSelf(), like a lot of stuff in Android, has no immediate effect. It puts a message on the message queue processed by the main application thread. The actual work of stopping the service will not even begin until sometime after onStartCommand() has returned.

Sundeep
  • 1,536
  • 5
  • 23
  • 35
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 3
    I figured it wasn't but I wasn't entirely sure of the inner workings of the Service class and calling a function that stops it from starting before it's even finished some start related event seems like it could result some unwanted behavior depending on how it was designed. – Spencer Ruport Nov 26 '11 at 20:31
  • 9
    @SpencerRuport: `stopSelf()`, like a lot of stuff in Android, has no immediate effect. It puts a message on the message queue processed by the main application thread. The actual work of stopping the service will not even begin until sometime after `onStartCommand()` has returned. – CommonsWare Nov 26 '11 at 21:51
  • 5
    As a follow-up question, what would be the appropriate return value having just called `stopSelf()`? – Mark Mar 28 '15 at 12:34
  • 17
    @MarkCarter: Presumably `START_NOT_STICKY`. – CommonsWare Mar 28 '15 at 12:38