Android: How to Stop service that is started by bindService() with BIND_AUTO_CREATE option?

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()?

Answer

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.