问题
I have a service that is started. In addition, other components can bind to the service. When a component binds to the service, it has new parameters it needs to deliver to the service. Is it possible to force onBind to be called each time a caller needs to bind (so as to deliver new data through intent)? And if so, is the additional overhead of calling onBind each time significant? BTW, this is a local service where I extend Binder instead of using Messenger.
回答1:
Few points to consider:
1) The onBind() is called only for the first binding request. All subsequent calls do not result in call to onBind. Here is excerpt from Google doc on this:
Multiple clients can connect to the service at once. However, the system calls your service's onBind() method to retrieve the IBinder only when the first client binds. The system then delivers the same IBinder to any additional clients that bind, without calling onBind() again.
So you should not expect onBind to be called each time a caller sends bind request.
2) Using the instance returned from onBind(), the callers can access public methods of the service. You can have one public method that will be used for sending any parameters. Here is Google doc on this:
If your service is private to your own application and runs in the same process as the client (which is common), you should create your interface by extending the Binder class and returning an instance of it from onBind(). The client receives the Binder and can use it to directly access public methods available in either the Binder implementation or even the Service.
3) Google recommends not to use any Extra parameters in the intent parameter of bindService. This may be due to point 1) mentioned above. Here is excerpt from Google doc:
The Intent that was used to bind to this service, as given to Context.bindService. Note that any extras that were included with the Intent at that point will not be seen here.
If there is no other need to make it a bound service, you can simply use it as a started service and pass extra parameters in the intent used for starting the service. That intent would be available in the onStartCommand(). If bind service is needed for other reasons, you can use option 2) above or follow the more complex approach mentioned here:
https://stackoverflow.com/a/9955090/4406743
来源:https://stackoverflow.com/questions/32574059/sending-data-to-a-bound-service