将数据发送到绑定服务 [英] Sending data to a bound service

查看:112
本文介绍了将数据发送到绑定服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个已启动的服务.此外,其他组件也可以绑定到服务.当组件绑定到服务时,它具有需要传递给服务的新参数.是否可以在每次调用者需要绑定时强制onBind调用(以便通过intent传递新数据)?如果是这样,每次调用onBind的额外开销是否很重要?顺便说一句,这是一个本地服务,我在其中扩展了Binder而不是使用Messenger.

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)仅对于第一个绑定请求调用onBind().所有后续调用均不会导致调用onBind.以下是Google文档的摘录:

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:

多个客户端可以一次连接到该服务.但是,仅当第一个客户端绑定时,系统才会调用服务的onBind()方法来检索IBinder.然后,系统将相同的IBinder传递给任何其他绑定的客户端,而无需再次调用onBind().

因此,您不应期望每次调用者发送绑定请求时都会调用onBind.

So you should not expect onBind to be called each time a caller sends bind request.

2)使用从onBind()返回的实例,调用者可以访问服务的公共方法.您可以使用一种公共方法来发送任何参数.这是有关此内容的Google文档:

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:

如果您的服务是您自己的应用程序专用的,并且在与客户端相同的进程中运行(这很常见),则应通过扩展Binder类并从onBind()返回它的一个实例来创建接口. .客户端收到Binder,并可以使用它直接访问Binder实现甚至服务中可用的公共方法.

3)Google建议不要在bindService的intent参数中使用任何其他参数.这可能是由于上述第1点.这是Google文档的摘录:

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:

用于绑定到此服务的Intent,如Context.bindService所给.请注意,此时在Intent中包含的任何其他内容都不会在这里显示.

如果没有其他需要使其成为绑定服务,则可以简单地将其用作已启动服务,并在用于启动该服务的意图中传递额外的参数.该意图将在onStartCommand()中可用.如果出于其他原因需要绑定服务,则可以使用上面的选项2)或遵循此处提到的更复杂的方法:

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

这篇关于将数据发送到绑定服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆