I'm developing an app which requires an Activity
to bind to a Service
. I'm using the usual bindService
and unbindService
. However, I'm trying to maintain the binding through orientation changes. For that, I'm overriding onRetainCustomNonConfigurationInstance
. But I'm facing to problems. To make the call to unbind
I check if the Activity
is finishing with isFinishing()
and works fine but an Exception
is being thrown warning a ServiceConnection
has been leaked. I don't know if this can be worked around.
My main problem is, if after a rotation a call to unbind
is made, I get an IllegalArgumentException
with message Service not registered
I'm keeping and unbinding the original ServiceConnection
but it is not working.
The binding is kept through orientation changes because Fragment
s attached to the Activity
are using the Service
too.
Is there anyway to fix this? Or should I make a ServiceConnection
in the Fragment
s too?
Thanks
You are getting exception ServiceConnection has been leaked is because when you tried to bind the service with the serviceconnection object , you have used Activity context. So this will create a leak when your device orientation changes and you are saving the ServiceConnection .
To avoid the leak,during binding and unbinding the service anywhere in your Activity, use Application Context(
getApplicationContext()
) , this will fix your issue and you won't be leaking the ServiceConnectionbinding:
unbinding: