Showing status bar notifications in Android

A status bar notification adds an icon to the system’s status bar with an optional ticker-text message and a notification message in the notifications window. When the user selects the notification, usually an Activity is opened. The notification can be configured to alert the user with a sound, a vibration, and flashing lights on the device.

In the example below a notification is fired imediatly and when user clicks on it, the PostNotification activity opens.

public void onCreate(Bundle savedInstanceState) {

   // Get a reference to the NotificationManager
   NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

   // Instantiate the Notification with an icon, ticker text, and when to be displayed
   int icon = R.drawable.ic_launcher;
   CharSequence tickerText = "New notification";
   long when = System.currentTimeMillis(); //now
   Notification notification = new Notification(icon, tickerText, when);

   // Define the notification's message and PendingIntent
   Context context = getApplicationContext();
   CharSequence title = "Notification title";
   CharSequence text = "Notification description";
   // The activity PostNotification.class will be fired when notification will be opened.
   Intent notificationIntent = new Intent(this, PostNotification.class);
   PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

   // Makes the notification disappear after clicked in the status bar

   // When the notification will be fired, notify the user with default notification phone sound.

   notification.setLatestEventInfo(context, title, text, pendingIntent);

   // Pass the Notification object to NotificationManager
   notificationManager.notify(1, notification);

If you’d like to try the example above, create a new Activity called: PostNotification, create a new layout file, say postnotification.xml and add in the PostNotification activity:


Ultimately, do not forget to register the PostNotification activity in the AndroidManifest file:

<activity android:name=".PostNotification"></activity>


3 thoughts on “Showing status bar notifications in Android

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s