How to create status bar notifications in android?


How to create status bar notifications in android?

To create a status bar notification, you will need to use two classes: Notification and NotificationManager.

    * ·  Notification – defines the properties of the status bar notification like the icon to display, the test to display when the notification first appears on the status bar and the time to display.
   
     * · NotificationManager is an android system service that executes and manages all notifications. Hence you cannot create an instance of the NotificationManager but you can retrieve a reference to it by calling the getSystemService() method.


Once you procure this handle, you invoke the notify() method on it by passing the notification object created.







Step 1: Procure a handle to the NotificationManager:


            private NotificationManager mNotificationManager;
      …
         mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);


Step 2: Create a notification object along with properties to display on the status bar


             final Notification notifyDetails =
                                  new Notification(R.drawable.android,"New Alert, Click Me!",System.currentTimeMillis());


Step 3: Add the details that need to get displayed when the user clicks on the notification. In this case, I have created an intent to invoke the browser to show the website http://www.android.com


                   Context context = getApplicationContext();
   
                   CharSequence contentTitle = "Notification Details...";
   
                   CharSequence contentText = "Browse Android Official Site by clicking me";

                   Intent notifyIntent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("http://www.android.com"));
   
                   PendingIntent intent = PendingIntent.getActivity(SimpleNotification.this, 0,
                                             notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
                 
                   notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);

Step 4: Now the stage is set. Notify.
     
                 mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);



in the beginning ,             private int SIMPLE_NOTFICATION_ID;


Now, you may realize that the constant SIMPLE_NOTIFICATION_ID becomes the way of controlling,

 updating, stopping a current notification that is started with the same ID.