Saturday, October 27, 2012

Android status bar notifications

This article provides a sample implementation for android status bar notifications. A notification is a message that is displayed outside the application's normal UI and visible when the user opens the notification drawer.

Notifications in the notification drawer appear in 2 visual styles.
  • Normal View - Appears in a view that is 64dp tall.
  • Big View - Appears as a normal view notification which can be expanded with a gesture.
This example below implements a Normal View notification. Adds a notification when the activity is created and clears when the activity is destroyed. This is useful in applications like music player, radio etc. where a notification indicates the current state (song being played) of the activity. The notification is also an entry point to enter into the activity. 

The application manifest for this example looks as below.
<manifest xmlns:android=""
    android:versionName="1.0" >

        android:targetSdkVersion="15" />

        android:theme="@style/AppTheme" >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

Note the inclusion of "singleTop" to the launchMode. If an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity.

The code to include and remove notification is quite simple. The notification icon, title and content are set using the NotificationCompat builder. We need to associate an action with the notification is tapped. This is achieved using the PendingIntent. In this example, we launch the activity as the intent. This would bring the activity to foreground since "singleTop" launch mode is specified.
// Add app running notification
private void addNotification() {

    NotificationCompat.Builder builder =
         new NotificationCompat.Builder(this)
         .setContentTitle("Notifications Example")
         .setContentText("This is a test notification");

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 

    // Add as notification
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

// Remove notification
private void removeNotification() {
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


  1. This comment has been removed by a blog administrator.

  2. This comment has been removed by a blog administrator.


Contact Form


Email *

Message *

Back to Top