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 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.

public Notification.Builder addAction(int icon, java.lang.CharSequence title, intent)
public Notification.Builder setContentIntent( intent)

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:

Notification notification = new Notification.Builder(context)
.setContentTitle(“New notification”)
.setContentText(“Youve got one!”)
.addAction(android.R.drawable.star_big_on, Open, pendingIntent)


To sound a ringtone, flash lights and make the device vibrate, you can OR the defaults flags like so:

notification.defaults|= Notification.DEFAULT_SOUND;

notification.defaults|= Notification.DEFAULT_LIGHTS;

notification.defaults|= Notification.DEFAULT_VIBRATE;

In addition, to make repeating sound, you can set the FLAG_INSISTENT flag.

notification.flags |= Notification.FLAG_INSISTENT;




Leave a Reply

Your email address will not be published. Required fields are marked *