27

I'm messing with Android services, and I have found that ServiceConnection.onServiceConnected() gets called fairly predictably when I bind to a service.

However, my onServiceDisconnected() method seems to never be called, even after the VM dies.

I have logged debug messages on the service and show that all threads have been shutdown, etc. I know services are implemented as processes; are there threads I don't know about that are preventing the process from exiting?

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
sehugg
  • 3,615
  • 5
  • 43
  • 60

1 Answers1

26

It happens upon remote service crash. So, if a service running in a different process than your client fails on some exception, you lose the connection and get the callback.

xpda
  • 15,585
  • 8
  • 51
  • 82
reflog
  • 7,587
  • 1
  • 42
  • 47
  • 2
    Is it just on crash? I would expect it to be called when I call `unbindService()` and the service exits because there are no more clients. – sehugg Jun 11 '09 at 20:09
  • 3
    according to the documentation it only happens on 'unexpected service unbinding' , so yes, it's only on crash, and no on unbindService() – reflog Jun 13 '09 at 15:08
  • 2
    So, how can you know if you can actually rebind to the service ? Or better, how do you rebind ? Uing a new ServiceConnection ? – Snicolas Oct 12 '12 at 01:11
  • 1
    @Reflog That's true, although when you have bound the service using Context.BIND_NOT_FOREGROUND you are able to see the onDisconnectedService everytime you stop the service and unbind it. Checkout this [Answer](http://stackoverflow.com/questions/13579965/how-to-force-the-onservicedisconnected-get-called) – Dino Nov 28 '12 at 08:08
  • 1
    You don't have to rebind; the connection remains even after the service has disconnected. If the service revives, your onServiceConnected() method will be called again. – Carl Feb 19 '13 at 00:39
  • @Carl, Yeah, as you said, after disconnection, android is connecting again. – Lazy Sep 03 '15 at 18:07
  • What gets called when the service is stopped? – android developer Oct 18 '16 at 12:50