Why would I use a Bound Service?

2019-04-10 09:31发布

问题:

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));

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

回答1:

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.

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.