Chapter 28 Background Services
Make PollService notify the user that a new result is ready by creating a Notification and calling
NotificationManager.notify(int, Notification).
Listing 28.17 Adding a notification (PollService.java)
@Override
protected void onHandleIntent(Intent intent) {
...
String resultId = items.get(0).getId();
if (resultId.equals(lastResultId)) {
Log.i(TAG, "Got an old result: " + resultId);
} else {
Log.i(TAG, "Got a new result: " + resultId);
Resources resources = getResources();
Intent i = PhotoGalleryActivity.newIntent(this);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
Notification notification = new NotificationCompat.Builder(this)
.setTicker(resources.getString(R.string.new_pictures_title))
.setSmallIcon(android.R.drawable.ic_menu_report_image)
.setContentTitle(resources.getString(R.string.new_pictures_title))
.setContentText(resources.getString(R.string.new_pictures_text))
.setContentIntent(pi)
.setAutoCancel(true)
.build();
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);
notificationManager.notify(0, notification);
}
QueryPreferences.setLastResultId(this, resultId);
}
Let’s go over this from top to bottom. First, you configure the ticker text and small icon by calling
setTicker(CharSequence) and setSmallIcon(int). (Note that the icon resource referenced is
provided as part of the Android framework, denoted by the package name qualifier android in
android.R.drawable.ic_menu_report_image, so you do not have to pull the icon image into your
resource folder.)
After that, you configure the appearance of your Notification in the drawer itself. It is
possible to create a completely custom look and feel, but it is easier to use the standard look
for a notification, which features an icon, a title, and a text area. It will use the value from
setSmallIcon(int) for the icon. To set the title and text, you call setContentTitle(CharSequence)
and setContentText(CharSequence), respectively.
Next, you must specify what happens when the user presses your Notification. Like
AlarmManager, this is done using a PendingIntent. The PendingIntent you pass into
setContentIntent(PendingIntent) will be fired when the user presses your Notification in the
drawer. Calling setAutoCancel(true) tweaks that behavior a little bit. With setAutoCancel(true)
set, your notification will also be deleted from the notification drawer when the user presses it.
Finally, you get an instance of NotificationManagerCompat from the current context
(NotificationManagerCompat.from(this)) and call NotificationManagerCompat.notify(...)
to post your notification. The integer parameter you pass to notify(...) is an identifier for your