I start service by using:
private ServiceConnection _serviceConnection = new ServiceConnection() {...}
bindService(new Intent(this, MainService.class), _serviceConnection, Context.BIND_AUTO_CREATE);
I want to 'restart' the service. (Let's not argue why I want to do that) I do that by:
unbindService(_serviceConnection);
// Do some initialization on service
bindService(new Intent(this, MainService.class), _serviceConnection, Context.BIND_AUTO_CREATE);
I noticed service doesn't die(onDestroy doesn't run) until I call next bindService(); So some static initialization I did on service got cleared by onDestroy() implementation.
Question: How do you make sure unbindService() will stop service (run onDestory()), so that I could do initialization after and re-run bindService()?
Android keeps services around at it's own discretion, even after calling unbindService
or stopService
.
If you need to immediately reinitialize some data on the service side, you most likely need to provide a service method for doing that.
Question: How do you make sure unbindService() will stop service (run onDestory()), so that I could do initialization after and re-run bindService()?
The timing of onDestroy()
after the last unbindService()
is indeterminate and certainly asynchronous. You could also try calling stopService()
yourself, but that too is asynchronous, so you don't know when it will be stopped.
I do not know of a reliable way for you to "restart" a service using the binding pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With