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();
    }
}

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 notification. It should be unique across your application. If you post a second notification with this same ID, it will replace the last notification you posted with that ID. This is how you would implement a progress bar or other dynamic visuals.

And that is it. Run your app and turn polling on. You should eventually see a notification icon appear in the status bar. In the notification tray you will see a notification indicating that new photo results are available.

After you are satisfied that everything is working correctly, change your alarm constant to be something more sensible. (Using one of AlarmManager’s predefined interval constants ensures that your app will get inexact repeating alarm behavior on pre-KitKat devices.)

Listing 28.18  Changing to a sensible alarm constant (PollService.java)

public class PollService extends IntentService {
    private static final String TAG = "PollService";

    // Set interval to 1 minute
    private static final long POLL_INTERVAL_MS = TimeUnit.MINUTES.toMillis(1);
    private static final long POLL_INTERVAL_MS = TimeUnit.MINUTES.toMillis(15);
    ...
}
..................Content has been hidden....................

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