0

I've read the official android docs and they say that

A bound service runs only as long as another application component is bound to it.

Thus, I understand that if I have an Activity and call a Service from that Activity, then when an activity is destroyed also the service is destroyed.

This work well when I press the back button and exit the application.

The problem is: when I rotate the screen the onDestroy() callback from the Activity is called, but the onDestroy() callback from the Service isn't called...

Taking into account the above citation from the official docs can someone explain me why this happens?

Note that I have only one activity bounded with that service.

Suraj Makhija
  • 1,376
  • 8
  • 16
Mateut Alin
  • 1,173
  • 4
  • 17
  • 34
  • The service will be destroyed once the last client unbinds from the service, if nobody called `startService()` on that service. When and where are you calling `unbindService()`? – CommonsWare Apr 10 '17 at 13:43
  • Are you unbinding the Activity from the Service? – DeeV Apr 10 '17 at 13:44
  • 1
    Simple: because it's too fast. Services don't just get destroyed immediately when they are not needed anymore. Usually they continue to run for a short time afterwards. The really important part here is: you are dealing with two completely different components with their own independent lifecycles. Your activity being destroyed means nothing to the service. All you know from the doc is that as long as clients are bound that the service won't be destroyed - but that doesn't mean that if no clients are bound that the service dies along with them. – Xaver Kapeller Apr 10 '17 at 13:47
  • @XaverKapeller Thank you. You're right! – Mateut Alin Apr 10 '17 at 13:53
  • @XaverKapeller Can you check out the tynn 's answer. It seems that the service must die along with the clients...? – Mateut Alin Apr 10 '17 at 14:01

1 Answers1

0

The documentation of Service states.

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().

Thus if you unbind with your activity destruction, don't have another connection bound to it or started the service directly, the service will be destroyed as well.

So make sure to unbind from the service as well.

tynn
  • 38,113
  • 8
  • 108
  • 143