28. Background Services
All the code you have written so far has been hooked up to an activity, which means that it is
associated with some screen for the user to look at.
But what if you do not need a screen? What if you need to do something out of sight and out of mind,
like play music or check for new blog posts on an RSS feed? For this, you need a service.
In this chapter, you will add a new feature to PhotoGallery that will allow users to poll for new search
results in the background. Whenever a new search result is available, the user will receive a notification
in the status bar.
Creating an IntentService
Let’s start by creating your service. In this chapter, you will use an IntentService. IntentService is
not the only kind of service, but it is probably the most common. Create a subclass of IntentService
called PollService. This will be the service you use to poll for search results.
Listing 28.1 Creating PollService (PollService.java)
public class PollService extends IntentService {
private static final String TAG = "PollService";
public static Intent newIntent(Context context) {
return new Intent(context, PollService.class);
}
public PollService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG, "Received an intent: " + intent);
}
}
This is a very basic IntentService. What does it do? Well, it is sort of like an activity. It
is a context (Service is a subclass of Context) and it responds to intents (as you can see in
onHandleIntent(Intent)). As a matter of convention – and to be a good citizen – you added
a newIntent(Context) method. Any component that wants to start this service should use
newIntent(Context).