Android:如何停止由bindService()使用BIND_AUTO_CREATE选项启动的服务?
我通过以下方式启动服务:
private ServiceConnection _serviceConnection = new ServiceConnection() {...}
bindService(new Intent(this, MainService.class), _serviceConnection, Context.BIND_AUTO_CREATE);
我想“重新启动”服务。 (我们不要争论为什么我要这么做) 我这样做的方法是:
unbindService(_serviceConnection);
// Do some initialization on service
bindService(new Intent(this, MainService.class), _serviceConnection, Context.BIND_AUTO_CREATE);
我注意到服务不会终止(onDestroy 不会运行),直到我调用下一个 bindService(); 因此,我在服务上所做的一些静态初始化被 onDestroy() 实现清除了。
问题:如何确保 unbindService() 将停止服务(运行 onDestory()), 这样我就可以在之后进行初始化并重新运行bindService()?
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()?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
即使在调用
unbindService
或stopService
之后,Android 也会自行决定保留服务。如果您需要立即在服务端重新初始化某些数据,您很可能需要提供一个服务方法来执行此操作。
Android keeps services around at it's own discretion, even after calling
unbindService
orstopService
.If you need to immediately reinitialize some data on the service side, you most likely need to provide a service method for doing that.
最后一次
unbindService()
之后onDestroy()
的计时是不确定的,而且肯定是异步的。您也可以尝试自己调用stopService()
,但这也是异步的,因此您不知道它何时会停止。我不知道您使用绑定模式“重新启动”服务的可靠方法。
The timing of
onDestroy()
after the lastunbindService()
is indeterminate and certainly asynchronous. You could also try callingstopService()
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.
如果 onUnbind() 返回 true,则可以使用 onRebind()。
参见这里:
http://developer.android.com/guide/components/bound-services.html
You can use onRebind() if you return true in onUnbind().
see here:
http://developer.android.com/guide/components/bound-services.html