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

A service’s intents are called commands. Each command is an instruction to the service to do something. Depending on the kind of service, that command could be serviced in a variety of ways.

An IntentService service pulls its commands off of a queue, as shown in Figure 28.1.

Figure 28.1  How IntentService services commands

Figure shows the execution of IntentService commands.

When it receives its first command, the IntentService starts, fires up a background thread, and puts the command on a queue.

The IntentService then services each command in sequence, calling onHandleIntent(Intent) on its background thread for each command. New commands that come in go to the back of the queue. When there are no commands left in the queue, the service stops and is destroyed.

This description only applies to IntentService. Later in the chapter, we will discuss the broader world of services and how commands work.

Because services, like activities, respond to intents, they must also be declared in your AndroidManifest.xml. Add an element for PollService to your manifest.

Listing 28.2  Adding service to manifest (AndroidManifest.xml)

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bignerdranch.android.photogallery" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        ... >
        <activity
            android:name=".PhotoGalleryActivity"
            android:label="@string/app_name" >
            ...
        </activity>
        <service android:name=".PollService" />
    </application>

</manifest>

Then add code to start your service inside PhotoGalleryFragment.

Listing 28.3  Adding service startup code (PhotoGalleryFragment.java)

public class PhotoGalleryFragment extends Fragment {

    private static final String TAG = "PhotoGalleryFragment";
    ...
    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        updateItems();

        Intent i = PollService.newIntent(getActivity());
        getActivity().startService(i);

        Handler responseHandler = new Handler();
        mThumbnailDownloader = new ThumbnailDownloader<>(responseHandler);
        ...
    }
    ...
}

Fire this up and see what you get. You should see something like this in Logcat:

02-23 14:25:32.450    2692-2717/com.bignerdranch.android.photogallery I/PollService:
 Received an intent: Intent { cmp=com.bignerdranch.android.photogallery/.PollService }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
34.227.112.145