Archive

Posts Tagged ‘notification’

Showing status bar notifications in Android

January 15, 2012 3 comments

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.


@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   // 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
   notification.flags|=Notification.FLAG_AUTO_CANCEL;

   // When the notification will be fired, notify the user with default notification phone sound.
   notification.defaults|=Notification.DEFAULT_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:


setContentView(R.layout.postnotification);

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


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

Follow

Get every new post delivered to your Inbox.

Join 485 other followers

%d bloggers like this: