5

对于应用程序和服务之间的通信,我为什么要使用绑定服务而不是在 Intent 中发送数据:

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

我读到“如果服务已经在运行,它将再次使用 onStartCommand() 调用,以传递新的 Intent,但不会创建第二个副本。” 这意味着我可以发送消息以影响服务的进度,这是在 google RandomMusicPlayer 示例中所做的:

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();
}
4

1 回答 1

0

绑定到服务而不是发送异步消息的原因有很多。一个重要的原因是它可以让您更好地控制服务的生命周期。如果您只是发送由服务处理的意图,那么服务很可能会在消息之间消失——丢失任何内部状态。当 Android 寻找可以释放的资源时,绑定服务会受到特殊处理。

另一个不相关的原因是,如果您绑定到进程内服务,您可以将 IBinder 强制转换为已知类并直接调用它的方法。这为服务提供了一个非常丰富(尽管紧密耦合)的接口。使用通过 Intent 传递消息来模拟这种丰富的交互是很困难的。

于 2013-02-20T20:41:34.833 回答