Android Notification, PendingIntent Example

Filed Under: Android

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="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://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.

References:

Comments

  1. babin tandukar says:

    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

  2. Ajit says:

    How will Notification come Automatically in any App.

    1. Anupam says:

      Notifications are pushed from the server. Received and displayed using Broadcast Receivers of the application.

    2. Beni says:

      You can use Firebase

  3. Joe says:

    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?

    1. EzKill69 says:

      Butterknife is a 3rd party library that makes everything easy and less messy…like for example
      instead of writing the whole code for declaring the view and then setting an onClickListener(),you can simply call OnClick() of butterknife and write the operation there.Take a look here http://jakewharton.github.io/butterknife/ its very useful

  4. jovylle says:

    OMG
    Perfect!
    the GIF
    AMAZING

    God Bless you
    Do more tutorials 🙂

    You deserve a 1 millions Views

  5. Eduardo says:

    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.

  6. jejoba.81@gmail.com says:

    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

    1. Pankaj says:

      Thanks for the feedback, i have corrected the typo error.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages