我为什么要使用绑定服务?

时间:2013-02-20 16:35:32

标签: android android-service

为了在应用程序和服务之间进行通信,为什么我会使用绑定服务而不是在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();
}

1 个答案:

答案 0 :(得分:0)

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

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