Is it possible to call Service.startService () from Service.onBind ()?

I have a service that I want to make sure DOES NOT stop () when there are no activities associated with it.

I understand that startService () is used to achieve this, but can this be called from the onBind () method?

Calling it from an action seems hacked to me because the service knows better whether it wants to turn around after onUnbind ().

Actions show the current status of the service and provide some control, so bindService () seems appropriate for use here.

+8
android android-service
source share
2 answers

It should be ok to call startService() from onBind() . If you have logic in onBind() that can determine that the service should stay the same, even if the client has an unrelated one, then this seems to be the logical place to do this.

I do not agree with the answer, which claims that it is not recommended. The architecture you described uses encapsulation effectively. Customers only want to bind / untie, and they don’t need to know how this service is (internally) implemented. The service must control its own life cycle.

+7
source share

Calling startService() from onBind() not recommended. onBind() is for connecting to clients, you should not change the behavior.

Before the client wants to connect, let it call startService() , if the service is already running, it will have no effect, the client object can then be bound. the service will continue to work when customers are untied. If the service knows when not to be near, you can safely call stopSelf() on yourself and exit.

0
source share

All Articles