Android mantain service connection through orientation change

1.1k views Asked by At

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 Activityis 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 Fragments attached to the Activity are using the Service too.

Is there anyway to fix this? Or should I make a ServiceConnection in the Fragments too?

Thanks

1

There are 1 answers

0
Hasif Seyd On BEST ANSWER

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 ServiceConnection

binding:

getApplicationContext().bindService(new Intent(this, TestService.class), serviceConnection, BIND_AUTO_CREATE); 

unbinding:

getApplicationContext().unbindService(serviceConnection)