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

ser*_*kye 5 android android-service

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

mServiceIntent = new Intent(getActivity(), RSSPullService.class);
mServiceIntent.setData(Uri.parse(dataUrl));
Run Code Online (Sandbox Code Playgroud)

我读到“如果服务已经在运行,它将再次使用 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();
}
Run Code Online (Sandbox Code Playgroud)

Dal*_*son 0

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

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