August 24,2016
A notification is a message you can display to the user outside of your application’s normal UI. You can create your own notifications in android very easily.
Android provides NotificationManager class for this purpose. In order to use this class, you need to instantiate an object of this class by requesting the android system through getSystemService() method. Its syntax is given below −
NotificationManager NM; NM=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
After that you will create Notification through Notification class and specify its attributes such as icon,title and time e.t.c. Its syntax is given below −
Notification notify = new Notification(android.R.drawable.stat_notify_more,title,System.currentTimeMillis());
The next thing you need to do is to create a PendingIntent by passing context and intent as a parameter. By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself.
PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(),0);
The last thing you need to do is to call setLatestEventInfo method of the Notification class and pass the pending intent along with notification subject and body details. Its syntax is given below. And then finally call the notify method of the NotificationManager class.
notify.setLatestEventInfo(getApplicationContext(), subject, body,pending); NM.notify(0, notify);
Apart from the notify method, there are other methods available in the NotificationManager class. They are listed below −
| Sr.No | Method & description |
|---|---|
| 1 | cancel(int id)
This method cancel a previously shown notification. |
| 2 | cancel(String tag, int id)
This method also cancel a previously shown notification. |
| 3 | cancelAll()
This method cancel all previously shown notifications. |
| 4 | notify(int id, Notification notification)
This method post a notification to be shown in the status bar. |
| 5 | notify(String tag, int id, Notification notification)
This method also Post a notification to be shown in the status bar. |