Android status bar notifications

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 package="com.sourcetricks.notificationsexample"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="15" /><applicationandroid:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name=".MainActivity"android:launchMode="singleTop"><intent-filter><action android_name="android.intent.action.MAIN" /><category android_name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

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 notificationprivate void addNotification() {NotificationCompat.Builder builder =new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setContentTitle("Notifications Example").setContentText("This is a test notification");Intent notificationIntent = new Intent(this, MainActivity.class);PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);builder.setContentIntent(contentIntent);// Add as notificationNotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);manager.notify(FM_NOTIFICATION_ID,;}// Remove notificationprivate void removeNotification() {NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);manager.cancel(FM_NOTIFICATION_ID);}