There is a simple method to create notification. Follow the following steps to create a notification.
STEP 1 - CREATE NOTIFICATION BUILDER
As a first step is to create a notification builder using NotificationCompat.Builder.build(). We will use Notification to set various Notification properties like its small and large icons,title,priority etc.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
STEP 2 - SETTING NOTIFICATION PROPERTIES
Once we have Builder object, we can set its Notification properties using Builder object as per our requirement. But this is mandatory to set atleast following:
- A small icon, set by setSmallIcon()
- A title, set by setContentTitle()
- Detail text, set by setContentText()
mBuilder.setSmallIcon(R.drawable.notification_icon); mBuiler.setContentTitle("Notification Alert, Click Me !"); mBuilder.setContentText("Hi, This is Android Notification Detail");
STEP 3 - ATTACH ACTIONS
This is an optional part and required if we want to attach an action with the application. An action allows users to go directly from the notification to an Activity in our application, where user can look at one or more events or do further work.
The action is defined by a PendingIntent containing an Intent that starts an Activity in our application. To asscociate the PendingIntent with a gesture, call the appropriate method of NotificationBuilder.Builder. For example, if we want to start Activity when user clicks the notification text in the notification drawer, you add the PendingIntent by calling setContentIntent().
A PendingIntent object helps us to perform an action on our application's behalf, often at a later time, without caring of whether or not our application is running.
We can help of stack builder object which will contain an artificial back stack for the started Activity. This ensure the navigating backward from the Activity leads out of our application to the Home screen.
Intent resultIntent = new Intent(this,ResultActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(ResultActivity.class); //Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT); mbuilder.setCotentIntent(resultPendingIntent);
STEP 4 - ISSUE THE NOTIFICATION
Finally, we can pass the Notification object to the system by calling NotificationManager.notifiy() to send our notification. Make sure we call NotificationCompat.Builder.build() method on builder object before notifying it. This method combines all of the options that have been set and return a new Notification object.
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); //notificatioID allows us to update the notification later on mNotificationManager.notify(notificationID, mBuilder.build());