// Tutorial //

Android Notification, PendingIntent Example

Published on August 3, 2022
Default avatar
By Anupam Chugh
Developer and author at DigitalOcean.
Android Notification, PendingIntent Example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Welcome to Android Notification Example using android PendingIntent. In this tutorial we’re going to discuss and implement PendingIntent and build Notification in our application.

Android PendingIntent

Android PendingIntent is an object that wraps up an intent object and it specifies an action to be taken place in future. In other words, PendingIntent lets us pass a future Intent to another application and allow that application to execute that Intent as if it had the same permissions as our application, whether or not our application is still around when the Intent is eventually invoked. A PendingIntent is generally used in cases were an AlarmManager needs to be executed or for Notification (that we’ll implement later in this tutorial). A PendingIntent provides a means for applications to work, even after their process exits. For security reasons, the base Intent that is supplied to the PendingIntent must have the component name explicitly set to ensure it is ultimately sent there and nowhere else. Each explicit intent is supposed to be handled by a specific app component like Activity, BroadcastReceiver or a Service. Hence PendingIntent uses the following methods to handle the different types of intents:

  1. PendingIntent.getActivity() : Retrieve a PendingIntent to start an Activity
  2. PendingIntent.getBroadcast() : Retrieve a PendingIntent to perform a Broadcast
  3. PendingIntent.getService() : Retrieve a PendingIntent to start a Service

An example implementation of PendingIntent is given below.

Intent intent = new Intent(this, SomeActivity.class);
// Creating a pending intent and wrapping our intent
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
try {
    // Perform the operation associated with our pendingIntent
} catch (PendingIntent.CanceledException e) {

The operation associated with the pendingIntent is executed using the send() method. The parameters inside the getActivity() method and there usages are described below :

  1. this (context) : This is the context in which the PendingIntent starts the activity
  2. requestCode : “1” is the private request code for the sender used in the above example. Using it later with the same method again will get back the same pending intent. Then we can do various things like cancelling the pending intent with cancel(), etc.
  3. intent : Explicit intent object of the activity to be launched
  4. flag : One of the PendingIntent flag that we’ve used in the above example is FLAG_UPDATE_CURRENT. This one states that if a previous PendingIntent already exists, then the current one will update it with the latest intent. There are many other flags like FLAG_CANCEL_CURRENT etc.

Android Notification

Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persistent which means alert flashes on the screen for a few seconds and then disappears. Android notification message fills up the void in such situations. Android notification is a message that we can display to the user outside of our application’s normal UI. Notifications in android are built using NotificationCompat library.

Creating Android Notification

A Notification is created using the NotificationManager class as shown below:

NotificationManager notificationManager = (NotificationManager) 

The Notification.Builder provides an builder interface to create an Notification object as shown below:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

Android Notification Methods

We can set the notification properties on this builder object. Some of the frequently used methods and there descriptions are given below.

  1. Notification build() : Combines all of the options that have been set and returns a new Notification object

  2. NotificationCompat.Builder setAutoCancel (boolean autoCancel) : Setting this flag will make it such that the notification is automatically canceled when the user clicks it in the panel

  3. NotificationCompat.Builder setContent (RemoteViews views) : Supplies a custom RemoteViews to use instead of the standard one

  4. NotificationCompat.Builder setContentInfo (CharSequence info) : Sets the large text at the right-hand side of the notification

  5. NotificationCompat.Builder setContentIntent (PendingIntent intent) : Supplies a PendingIntent to send when the notification is clicked

  6. NotificationCompat.Builder setContentText (CharSequence text) : Sets the text (second row) of the notification, in a standard notification

  7. NotificationCompat.Builder setContentTitle (CharSequence title) : Sets the text (first row) of the notification, in a standard notification

  8. NotificationCompat.Builder setDefaults (int defaults) : Sets the default notification options that will be used. An example is;

    mBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
  9. NotificationCompat.Builder setLargeIcon (Bitmap icon) : Sets the large icon that is shown in the ticker and notification

  10. NotificationCompat.Builder setNumber (int number) : Sets the large number at the right-hand side of the notification

  11. NotificationCompat.Builder setOngoing (boolean ongoing) : Sets whether this is an ongoing notification

  12. NotificationCompat.Builder setSmallIcon (int icon) : Sets the small icon to use in the notification layouts

  13. NotificationCompat.Builder setStyle (NotificationCompat.Style style) : Adds a rich notification style to be applied at build time

  14. NotificationCompat.Builder setTicker (CharSequence tickerText) : Sets the text that is displayed in the status bar when the notification first arrives

  15. NotificationCompat.Builder setVibrate (long[] pattern) : Sets the vibration pattern to use

  16. NotificationCompat.Builder setWhen (long when) : Sets the time that the event occurred. Notifications in the panel are sorted by this time

Android Notification Button and Styles

The Notification.Builder allows you to add up to three buttons with definable actions to the notification. Android 4.1 and above support expandable notifications which shows a big view of the notification when it is expanded. There are three styles that can be used with the big view: big picture style, big text style, Inbox style.

Cancelling Android Notification

We can also call the cancel() for a specific notification ID on the NotificationManager. The cancelAll() method call removes all of the notifications you previously issued. In this tutorial we’ll create an application that wraps an intent that would view a webpage, into a PendingIntent. That PendingIntent would fire when the notification is tapped upon. Also we’ll add the feature that cancels the notification programmatically too.

Android Notification Example Project Structure

android notification example

Android Notification Example

The activity_main.xml is a basic relative layout with two buttons : One to create a notification and the other to cancel it. activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"

        android:text="CREATE NOTIFICATION"
        android:layout_alignParentStart="true" />

        android:text="CANCEL NOTIFICATION"
        android:layout_alignParentStart="true" />

The MainActivity.java is given below.

package com.journaldev.notifications;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {

    public void sendNotification() {

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com/"));
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentTitle("Notifications Title");
        builder.setContentText("Your notification content here.");
        builder.setSubText("Tap to view the website.");

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        // Will display the notification in the notification bar
        notificationManager.notify(1, builder.build());

    public void cancelNotification() {

        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);

In the above code we’ve passed an intent of this website into the PendingIntent. The notificationId is set to 1 and it’s used to build the notification and cancel it. The output of the app in action is given below. android notification example, android pendingintent example This brings an end to android notification using PendingIntent tutorial. You can download the Android Notification Project from the link below.

Download Android PendingIntent and Notifications Project


If you’ve enjoyed this tutorial and our broader community, consider checking out our DigitalOcean products which can also help you achieve your development goals.

Learn more here

About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?

How to open a specific activity on push notification tapped?

- Prashant

    Sir how can we implement Notification from server with php mysql and fcm

    - Hazrat Bilal

      Hi Anupam Just a query as I am not a developer I am observing that Whatsapp is not notifying users with sound & vibration randomly, icon appears in notification tray but without sound & vibration intermittently. Is this a Whatsapp bug or Android bug?

      - Naman Khanna

        You are using implicit intent and pass it to the PendingIntent, but if there is no application to handle your intent (in this case web browser to open specified url) your application will crash when you click on Notification.

        - Andjela

          hello really need help my pending intent from notification is not working while app isclosed or inbackground it starts default intent …but its fine if app is open . Same code is working on my previous project

          - babin tandukar

            How will Notification come Automatically in any App.

            - Ajit

              Hello, Thank you for your tutorial. I was wondering what was the relevance of the following code (inside the MainActivity.java): import [butterknife].ButterKnife; import [butterknife].OnClick; [ButterKnife].inject(this); @[OnClick](R.id.button) …new NotificationCompat([this]) <<< NotificationCompat cannot be applied to MainActivity Everything I placed in brackets ( [ ] ), is in red or red underline. I did not see anything attached to the tutorial zip file that contained anything that mentioned ‘butterknife’. How can I resolve this?

              - Joe

                OMG Perfect! the GIF AMAZING God Bless you Do more tutorials :) You deserve a 1 millions Views

                - jovylle

                  Hello, I have a problem when creating a notification. I have to create a notification which should arise 1 day before the date of an event. However, the notification appears immediately after the event. The setWhen () and setShowWhen () are set correctly.

                  - Eduardo

                    Sir, You need to correct getService() and getBroadcast() descriptions. It’s a typo PendingIntent.getBroadcast() : Retrieve a PendingIntent to start a Service PendingIntent.getService() : Retrieve a PendingIntent to perform a Broadcast

                    - jejoba.81@gmail.com