Raphael Royer-Rivard
Raphael Royer-Rivard

Reputation: 2252

How to properly unbind services

I have a Service that is binded with BIND_AUTO_CREATE to my Activity and is started with START_STICKY. I do not explicitly call startService().

Since the onDestroy() method is not always called when my Activity get killed and the onStop() method is not viable since I don't want my Service to stop when the user simply presses the Home button, I don't know when to unbind my Service.

Here are my questions :

  1. If I want my Service to run when my Activity is alive and to stop when my Activity get killed, where should I unbind my Service?

  2. When the onDestroy() method is currently called and I call unbindService(), the Service's onUnbind() method isn't triggered. Why?

Upvotes: 6

Views: 5447

Answers (1)

kiruwka
kiruwka

Reputation: 9450

I do not explicitly call startService()

In that case it doesn't make sense to override onStartCommand (and return START_STICKY) as it won't be called.

1.If I want my Service to run when my Activity is alive and to stop when my Activity get killed, where should I unbind my Service?

if you don't want to do it in onPause, you can unbind in onDestroy, that is fine. In a rare situation when your activity gets killed without onDestroy it will be unbound by Android, (so your service will be unbound & destroyed properly too), as stated here :

When your client is destroyed, it will unbind from the service

As for

2.When the onDestroy() method is currently called and I call unbindService(), the Service's onUnbind() method isn't triggered. Why?

I suggest that you have someone else bound to it, otherwise onUnbind should be called. Try putting a breakpoint in this method and verify it gets hit. Also, verify that your service onDestroy is called in this situation.

Upvotes: 4

Related Questions