Saturday, August 30, 2014

How to create a simple status bar notification in Android

Notifications are the message that you can display to the user out side of your application's UI. When an application issue a notification, it will display within the notification area. Then user can expand the notification drawer to view full set of the the notifications that have been raised by the applications.

There are basically two types of the Notification Views:
  1. Normal view - can display small icon, title, message, notification issued time, count
  2. Big view - can define multiple messages, summary text, Big view style ..etc
Note: If you are planning to issue a notification via application, there should be at least an action to to raise once the user clicks the notification. eg: for an music player you may have pause, play, next..etc. 

Within this example will create a simple notification for the android devices: Click here to view How to create custom notification tutorial for extended status bar notifications.  You can check out how to update status bar notification blog post to know functionality of the  NotificationManager.notify(ID, notification). Using this method you can keep updating same notification within the notification area. such as email unread count, no of files uploaded...etc.

private void creaeSimpleNotification() {
  // Action one
  Intent dismissIntent = new Intent(this, MainActivity.class);
  dismissIntent.setAction("OFF");
  PendingIntent piDismiss = PendingIntent.getService(this, 0,
    dismissIntent, 0);

  // Action two
  Intent snoozeIntent = new Intent(this, MainActivity.class);
  snoozeIntent.setAction("ON");
  PendingIntent piSnooze = PendingIntent.getService(this, 0,
    snoozeIntent, 0);

  // Create notification builder to add notification
  NotificationCompat.Builder builder = new NotificationCompat.Builder(
   this.getApplicationContext())
   .setContentTitle("This is notification title")
   .setContentText("This is notification contnent")
   .setSmallIcon(R.drawable.notification_small_icon)
   .setStyle(new NotificationCompat.BigTextStyle())
   .addAction(R.drawable.notification_small_icon, "Off", piDismiss)  // Add action one   .addAction(R.drawable.notification_small_icon, "On", piSnooze); // Add action two
  Intent intent = new Intent(this, MainActivity.class);
  PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
    intent, 0);

  builder.setContentIntent(pendingIntent);
  NotificationManager notificationMgt = (NotificationManager) getSystemService(
                                                     Context.NOTIFICATION_SERVICE);
  notificationMgt.notify(9999, builder.build());
 }

Then onCreate method add above method as shown below:
        @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  creaeSimpleNotification();
 }


Output

No comments:

Post a Comment