Notifications
Notifications
Your service is now running and doing its thing in the background. But the user never knows a thing
about it, so it is not worth much.
When your service needs to communicate something to the user, the proper tool is almost always a
notification. Notifications are items that appear in the notifications drawer, which the user can access
by dragging it down from the top of the screen.
To post a notification, you first need to create a Notification object. Notifications are created by
using a builder object, much like the AlertDialog that you used in Chapter 12. At a minimum, your
Notification should have:
- ticker text to display in the status bar when the notification is first shown on pre-Lollipop devices
(starting with Android 5.0 [Lollipop], ticker text is no longer displayed in the status bar but is still
relevant for accessibility services) - an icon to show in the status bar (appears after the ticker text goes away on pre-Lollipop devices)
- a view to show in the notification drawer to represent the notification itself
- a PendingIntent to fire when the user presses the notification in the drawer
Once you have created a Notification object, you can post it by calling notify(int, Notification)
on the NotificationManager system service.
First you need to add some plumbing code, as shown in Listing 28.16. Open PhotoGalleryActivity
and add a static newIntent(Context) method. This method will return an Intent instance
that can be used to start PhotoGalleryActivity. (Eventually PollService will call
PhotoGalleryActivity.newIntent(...), wrap the resulting intent in a PendingIntent, and set that
PendingIntent on a notification.)
Listing 28.16 Adding newIntent(...) to PhotoGalleryActivity
(PhotoGalleryActivity.java)
public class PhotoGalleryActivity extends SingleFragmentActivity {
public static Intent newIntent(Context context) {
return new Intent(context, PhotoGalleryActivity.class);
}
@Override
protected Fragment createFragment() {
return PhotoGalleryFragment.newInstance();
}
}