Advertisement

Android Fundamentals: Status Bar Notifications

Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →
This post is part of a series called Android Fundamentals.
Android Fundamentals: Scheduling Recurring Tasks
Android Fundamentals: Database Dates and Sorting

Often times, applications will perform some background operation—maybe while the app is running or maybe triggered on a scheduled alarm. The user won't know what's going on, though, unless they are informed of some event. Luckily, Android has an easy notification system that allows applications to display a message in the status bar and provide informative details to the user when something important occurs.

In this tutorial, we'll extend the existing unnamed "TutList" application to notify the user when the scheduled download of tutorials has taken place. When the user taps on the notification in the status bar, the application will be launched. This way, we use notifications to provide feedback to the user that something has happened, while also reminding he user of the existence of the application and that fresh content is available.

Step 0: Getting Started

This tutorial assumes you start where our last "TutList" tutorial left off. You can download that code and work from it, or you can simply download or view the code provided with this tutorial and follow along. The choice is yours. We're on Version Code 9. The "tags" view of the source viewer has each version, for convenience.

Step 1: Android Notifications

The Android notification system is highly praised by users and developers. It's easy to use, flexible, and convenient. This tutorial will not cover every detail of the notification system. Instead, we'll focus on getting specific notifications working for the TutList application.

Generally speaking, notifications in the status bar at the top of the users screen (or the bottom on tablets running Android 3.0) appear as an icon and some short text. When the status bar is "pulled down", the user can see more notification details. These details can be drawn in a default way or they can be drawn using a custom RemoveViews object if you want to get fancy. Additionally, notifications can play sounds or flash colorful lights. Notifications can also display once, display persistently (for instance, to update the progress of an ongoing task), or display a count of items (for instance, to display the number of new emails).

We will create a simple notification that informs the user when the list of tutorials, in XML format, has been downloaded and parsed.

Let's start by getting an instance of the NotificationManager object, the base object with which notifications are handled. We'll start by adding code to the onPostExecute() method of the DownloaderTask inner class found in the TustListDownloaderService.

The following Java code retrieves an instance using the application context:

Context context = TutListDownloaderService.this
    .getApplicationContext();
NotificationManager notificationManager = (NotificationManager) context
    .getSystemService(NOTIFICATION_SERVICE);

Step 2: Creating a Notification

A Notification object encapsulates the information used to display a new notification to a user or to update an existing notification. Because existing notifications can be updated, the creation of a notification comes in two parts. First, the notification's core data is configured--the icon to be displayed in the status bar, the brief text displayed in the status bar, and the time of the notification are created separate from a notification event. The notification event, which consists of the specifics to show the user,

Let's create the notification:

Notification updateComplete = new Notification();
updateComplete.icon = android.R.drawable.stat_notify_sync;
updateComplete.tickerText = context
    .getText(R.string.notification_title);
updateComplete.when = System.currentTimeMillis();

Here, we set the icon to one of the system icons. For your own app, it's probably best to create your own set of icons. Google has a great resource on creating status bar icons for Android 2.3 and later as well as Android 2.2 and earlier found with the developer documentation icon guidelines. The ticker text is displayed briefly in the status bar right when the notification fires. The time (the "when" field) is used to show the user when the notification occurred.

Note: While using Notification.Builder may be simpler, it's only available in SDK Level 11 and later.

Step 3: Creating a PendingIntent

Notifications can trigger an Intent when tapped. They use the PendingIntent object to do this. A PendingIntent simply wraps a regular Intent inside an object such that another application can send the original Intent as if your application had done so. When the user taps on the notification, we just want the application to launch, so creating this PendingIntent object is easy:

Intent notificationIntent = new Intent(context,
    TutListActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
    notificationIntent, 0);

Step 4: Preparing the Notification Event

The default displayed notification event consists of a title and some informational text to tell the user what the notification is for. The event also uses the PendingIntent object we just created. We'll load text based on whether or not the download and parse was successful.

String contentTitle = context.getText(R.string.notification_title)
    .toString();

String contentText;
if (!result) {
    Log.w(DEBUG_TAG, "XML download and parse had errors");
    contentText = context.getText(R.string.notification_info_fail)
        .toString();
} else {
    contentText = context.getText(
        R.string.notification_info_success).toString();
}
updateComplete.setLatestEventInfo(context, contentTitle,
    contentText, contentIntent);

After loading the text, the setLatestEventInfo() method updates the notification with the most recent information you want to provide to the user. We're only doing this notification once per download (as opposed to giving download status), but it could be used to display various status updates as a task proceeds.

Step 5: Notifying the User

Finally, we return to the NotificationManager object and use its notify() method to actually show the notification to the user (or update it if it's changed).

notificationManager.notify(LIST_UPDATE_NOTIFICATION, updateComplete);

The first parameter of the notify() method is an application unique identifier. We've defined this within the TutListDownloaderService class to be a value of 100, although the value just needs to be unique – and it is since we have no other notifications.

That's all for displaying simple notifications in the status bar.

The following image shows what the notification looks like. It displays when the user manually downloads the latest articles or when the list is automatically updated daily.

Conclusion

ou have learned how to present notifications to users in this quick tutorial. The notification system is very flexible, but also easy when you just need a simple notification displayed. Your users will benefit from notifications by seeing what is going on in the background and being reminded about the application.

About the Authors

Mobile developers Lauren Darcey and Shane Conder have coauthored several books on Android development: an in-depth programming book entitled Android Wireless Application Development and Sams Teach Yourself Android Application Development in 24 Hours. When not writing, they spend their time developing mobile software at their company and providing consulting services. They can be reached at via email to androidwirelessdev+mt@gmail.com, via their blog at androidbook.blogspot.com, and on Twitter @androidwireless.

Need More Help Writing Android Apps? Check out our Latest Books and Resources!

Buy Android Wireless Application Development, 2nd Edition  Buy Sam's Teach Yourself Android Application Development in 24 Hours  Mamlambo code at Code Canyon

Advertisement