为什么我会用绑定的服务? [英] Why would I use a Bound Service?

查看:177
本文介绍了为什么我会用绑定的服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关应用和服务之间的通信,为什么我会用绑定的服务,而不是意图发送数据:

For communicating between the application and a Service, why would I use a Bound service rather than sending data in the Intent:

mServiceIntent = new Intent(getActivity(), RSSPullService.class);
mServiceIntent.setData(Uri.parse(dataUrl));

我读如果服务已在运行,它将被onStartCommand()再次呼吁,为客户提供新的意图,但不是会创建第二个副本。这意味着我可以在这意图影响服务的进程发送消息,这是在谷歌RandomMusicPlayer例子完成的:

I read that "If the service is already running, it will be called with onStartCommand() again, to deliver the new Intent, but a second copy is not created." Which means that I Could send messages in that intent to affect the service's progress, this is what is done in the google RandomMusicPlayer example:

public void onClick(View target) {
    // Send the correct intent to the MusicService, according to the 
    // button that was clicked
    if (target == mPlayButton)
        startService(new Intent(MusicService.ACTION_PLAY));
    else if (target == mPauseButton)
        startService(new Intent(MusicService.ACTION_PAUSE));
    else if (target == mSkipButton)
        startService(new Intent(MusicService.ACTION_SKIP));
    else if (target == mRewindButton)
        startService(new Intent(MusicService.ACTION_REWIND));
    else if (target == mStopButton)
        startService(new Intent(MusicService.ACTION_STOP));
    else if (target == mEjectButton) {
        showUrlDialog();
}


推荐答案

有若干原因,而不是将其发送异步消息绑定到服务。一个重要原因是它给你一个服务的生命周期进行更多的控制。如果你简单地发送由服务处理的意图,该服务可能消失 - 失去任何内部状态 - 消息之间。服务绑定时收到的Andr​​oid正在寻找可以释放资源的特殊待遇。

There are a number of reasons for binding to a Service as opposed to sending it asynchronous messages. One important reason is it gives you more control of the lifetime of a service. If you are simply sending intents that are handled by the service, the service may well go away -- losing any internal state -- between messages. Bound services receive special treatment when Android is looking for resources that can be freed.

另外,不相关的,原因是,如果你绑定到一个进程内服务,您可以直接施放的IBinder到一个已知的类调用方法就可以了。这提供了非常丰富(尽管紧密耦合)接口​​到服务。这将是很难用通过消息传递意图来模拟这一丰富的互动。

Another, unrelated, reason is if you are binding to an in-process service you can cast the IBinder to a known class and call methods on it directly. This provides a very rich (although tightly coupled) interface to the service. It would be difficult to simulate this rich interaction using message passing via Intents.

这篇关于为什么我会用绑定的服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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