With a little bit of work, Services give us the means to perform long-running background tasks, and free us from the tyranny of the Activity
lifecycle. Unlike IntentService
, directly subclassing Service
also gives us the ability control the level of concurrency.
With the ability to run as many tasks as we need and to take as long as is necessary to complete those tasks, a world of new possibilities opens up.
The only real constraint on how and when we use Services comes from the need to communicate results to a user-interface component, such as a Fragment
or Activity
, and the complexity this entails.
Ideal use cases for Services tend to have the following characteristics:
Activity
or Fragment
classIntentService
provides, or needs control over the level of concurrencyThere are many applications that exhibit these characteristics, but the stand-out example is, of course, handling concurrent downloads from a web service.
To make good use of the available download bandwidth and to limit the impact of network latency, we want to be able to run more than one download at a time (but not too many). We also don't want to use more bandwidth than necessary by failing to completely download a file and having to restart the download later. So ideally, once a download starts, it should run to completion even if the user leaves the application.
In the accompanying downloads from the Packt Publishing website, you can find a complete example of using a Service
to download NASA's "Image of the Day" RSS, parse the XML in the background to extract the titles and URLs of the images, and download and display those images.
18.118.141.81