Android Notifications

A notification is a message on the status bar. Unlike a toast, a notification is persistent and will keep showing until it is closed or the device is shut down.

A notification is an instance of android.app.Notification. The most convenient way to create a notification is by using a nested class called Builder, which can be instantiated by passing a Context. You can then call the build method on the builder to create a Notification.

Notification n = new Notification.Builder(context).build();

The Notification.Builder class has methods to decorate the resulting notification. These methods include addAction, setAutoCancel, setColor, setContent, setContentTitle, setContentIntent, setLargeIcon, setSmallIcon and setSound.

Many of these methods are self-explanatory, but addAction and setContentIntent are of particular importance because you can use them to add an action that will be performed when the user touches the notification. In this case, a notification action is represented by a PendingIntent. Here are the signatures of addAction and setContentIntent, both of which take a PendingIntent.

When the user touches the notification, the send method of the PendingIntent will be invoked. See the sidebar for a description of PendingIntent.

setAutoCancel is also important and passing true to it allows the notification to be dismissed when the user touches it on the notification drawer. The notification drawer is an area that opens when you slide down the status bar. The notification drawer shows all notifications that the system have received and have not been dismissed.

The methods in Notification.Builder return the same Builder object, so they can be cascaded: