Showing Notifications

We will create a simple app that does nothing but display a notification to the user. Create a new project and jump to MainActivity class. We will add all our code in the onCreate method. You can later integrate this code into your apps as and when necessary.

First, create an object for Notification and use Notification Builder in the current Application Context. Under this there are number of options. If you are using Android Studio just type in a dot after creating the object and let the Android Studio display all the options that you can use which will look something like this..

Notification Options

In this example we will display an alert to the user that the cab he booked has arrived. We can set title and message using the setContentTitle and setContentText options.

We can also redirect the user to our app or any page that we want to by using an setContentIntent here.

.setContentIntent(pendingIntent)

To achieve this we have to create a Pending Intent as follows:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, intent, 0);

Then we will use this pendingIntent variable inside the setContentIntent method.

If you want to allow the user to call the driver directly from the notification we can also add a button to make it perform an action upon clicking using the addAction method as follows:

.addAction(android.R.drawable.sym_action_call, "Call Driver", pendingIntent)

You can set any Pending Intent here to redirect or call for an action just like we did before. This might give errors in Nougat.

Also set an icon to display alongside the notification with a simple setSmallIcon method. Here we display the app icon.

.setSmallIcon(android.R.drawable.sym_def_app_icon)

Now that we have set all the required information to be displayed, we display the content using Notification Manager as follows:

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);

That’s all the code we have to write to display a notification to the user. The whole code under the onCreate method looks like this..

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, intent, 0);

Notification notification = new Notification.Builder(getApplicationContext())
        .setContentTitle("Your Cab Has Arrived")
        .setContentText("White Honda City TS07UB1234. Driver's name is Kapil Sharma")
        .setContentIntent(pendingIntent)
        .setSmallIcon(android.R.drawable.sym_def_app_icon)
        .build();

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);

Leave a Reply

Your email address will not be published. Required fields are marked *