Tutorial

Android Notification, PendingIntent Example

Published on August 3, 2022
Default avatar

By Anupam Chugh

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
    pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
    e.printStackTrace();
}

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) 
  getSystemService(NOTIFICATION_SERVICE); 

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"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.journaldev.notifications.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CREATE NOTIFICATION"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CANCEL NOTIFICATION"
        android:id="@+id/button2"
        android:layout_below="@+id/button"
        android:layout_alignRight="@+id/button"
        android:layout_alignEnd="@+id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

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 {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
    }

    @OnClick(R.id.button)
    public void sendNotification() {

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com/"));
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentIntent(pendingIntent);
        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());
    }

    @OnClick(R.id.button2)
    public void cancelNotification() {

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

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

References:

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Anupam Chugh

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 12, 2021

How to open a specific activity on push notification tapped?

- Prashant

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    March 9, 2021

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

    - Hazrat Bilal

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      November 26, 2020

      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

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        February 4, 2020

        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

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          July 23, 2019

          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

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            August 22, 2017

            How will Notification come Automatically in any App.

            - Ajit

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              November 14, 2016

              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

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                September 16, 2016

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

                - jovylle

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 3, 2016

                  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

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    July 6, 2016

                    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

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more
                      DigitalOcean Cloud Control Panel