Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 643
jclova Avatar asked Nov 18 '10 16:11

jclova


2 Answers

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.

like image 158
Timo Ohr Avatar answered Sep 22 '22 20:09

Timo Ohr


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.

like image 38
CommonsWare Avatar answered Sep 19 '22 20:09

CommonsWare