开发者

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

开发者 https://www.devze.com 2023-01-25 23:37 出处:网络
I start service by using: private ServiceConnection _serviceConnection = new ServiceConnection() {...}

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:

unbindSe开发者_运维百科rvice(_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.


You can use onRebind() if you return true in onUnbind().

see here: http://developer.android.com/guide/components/bound-services.html

0

精彩评论

暂无评论...
验证码 换一张
取 消