Thursday, March 20, 2014

Android Tip - Displaying Notifications

In Android, a good way to notify the user outside of your application is through posting a notification in the notification area of the device. The notification will appear until the user opens the notification drawer and taps on it. Usually, tapping the notification will launch the application that displays the notification.

To create a notification, use the NotificationCompat.Builder class to create a Notification object, as shown in the following method:

    private void postNotification(String title, String msg) {
        //---which activity should be launched when the
        // notification is tapped---        
        Intent resultIntent = new Intent(this,
        PendingIntent pendingIntent =
        //---create a notification---
        Notification notification = new
        //---set the sound and lights---
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.defaults |= Notification.DEFAULT_LIGHTS;
        //---display the notification---

Each notification is identified using a notification id. Posting another notification using the same id replaces the previous notifications. You also need to use the NotificationManager class to post the notification:

public class MainActivity extends Activity { 
    private static final int NOTIFICATION_ID = 123;
    NotificationManager notificationManager;

    protected void onCreate(Bundle savedInstanceState) {
        notificationManager = (NotificationManager)

You can now post a notification by calling the method that you have just defined:

            "A sample notification",
            "Just testing the notification...");  

No comments: