Being a good citizen: using alarms the right way
After that, you need to either set the alarm or cancel it.
To set the alarm, you call AlarmManager.setRepeating(...). This method also takes four parameters: a
constant to describe the time basis for the alarm (more on that in a moment), the time at which to start
the alarm, the time interval at which to repeat the alarm, and finally a PendingIntent to fire when the
alarm goes off.
Because you used AlarmManager.ELAPSED_REALTIME as the time basis value, you specified the start
time in terms of elapsed realtime: SystemClock.elapsedRealtime(). This triggers the alarm to go off
when the specified amount of time has passed. If you had used AlarmManager.RTC, you would instead
base the start time on “clock time” (e.g., System.currentTimeMillis()). This would trigger the alarm
to go off at a fixed point in time.
Canceling the alarm is done by calling AlarmManager.cancel(PendingIntent). You will also usually
want to cancel the PendingIntent. In a moment, you will see how canceling the PendingIntent also
helps you track the status of the alarm.
Add some quick test code to run your alarm from within PhotoGalleryFragment.
Listing 28.9 Adding alarm 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);
PollService.setServiceAlarm(getActivity(), true);
Handler responseHandler = new Handler();
mThumbnailDownloader = new ThumbnailDownloader<>(responseHandler);
...
}
...
}
Finish typing in this code and run PhotoGallery. Then immediately hit the Back button and exit out of
the app.
Notice anything in Logcat? PollService is faithfully chugging along, running again every 60 seconds.
This is what AlarmManager is designed to do. Even if your process gets shut down, AlarmManager will
keep on firing intents to start PollService again and again. (This behavior is, of course, extremely
annoying. You may want to uninstall the app until we get it straightened out.)
Being a good citizen: using alarms the right way
How exact do you need your repeating to be? Repeatedly executing work from your background
service has the potential to eat up the user’s battery power and data service allotment. Furthermore,
waking the device from sleep (spinning up the CPU when the screen was off to do work on your
behalf) is a costly operation. Luckily, you can configure your alarm to have a lighter usage footprint in
terms of interval timing and wake requirements.