tags:

views:

79

answers:

2

Hello,I would like to know if it is possible to have a service that is started with startService and then be able to also bind to that service and do some remote procedure calls? according to this:http://developer.android.com/guide/topics/fundamentals.html#servlife

the two services have different lifecycle so it's not possible,does anyone know about it? thanks in advanced maxsap.

A: 

If you start a service using startService(), then you should stop it using stopService().

There are two reasons that a service can be run by the system. If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

You could bind to the service as many ServiceConnection as you want with bindService(), but pay attention to the flag you passed to it. If you pass 0 then if you call stopService() the service will stopped(i don't know exacltly what happens to you ServiceConnection). Otherwise if you want your service alive untill the ServiceConnection is binded to it then use BIND_AUTO_CREATE.

this is from stopService():

Request that a given application service be stopped. If the service is not running, nothing happens. Otherwise it is stopped. Note that calls to startService() are not counted -- this stops the service no matter how many times it was started.

Note that if a stopped service still has ServiceConnection objects bound to it with the BIND_AUTO_CREATE set, it will not be destroyed until all of these bindings are removed. See the Service documentation for more details on a service's lifecycle.

This function will throw SecurityException if you do not have permission to stop the given service.

i hope this helps..

hara
A: 

I think hara's answer was a little confusing. What you describe is perfectly legitimate and in fact the only way to get the behavior you want. If you create a service by binding to it, it will die when you unbind. So the only way to keep it around without activities binding to it is to start it with startService(). There is no conflict with lifecycles because it only applies to how the service is STARTED. So once it's started with startService(), it follows that lifecycle process. So you are free to bind and unbind to it as much as you wish and it will only die when you call stopService() or stopSelf()

Falmarri