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 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:
PendingIntent.getActivity()
: Retrieve a PendingIntent to start an ActivityPendingIntent.getBroadcast()
: Retrieve a PendingIntent to perform a BroadcastPendingIntent.getService()
: Retrieve a PendingIntent to start a ServiceAn 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 :
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.
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);
We can set the notification properties on this builder object. Some of the frequently used methods and there descriptions are given below.
Notification build() : Combines all of the options that have been set and returns a new Notification object
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
NotificationCompat.Builder setContent (RemoteViews views) : Supplies a custom RemoteViews to use instead of the standard one
NotificationCompat.Builder setContentInfo (CharSequence info) : Sets the large text at the right-hand side of the notification
NotificationCompat.Builder setContentIntent (PendingIntent intent) : Supplies a PendingIntent to send when the notification is clicked
NotificationCompat.Builder setContentText (CharSequence text) : Sets the text (second row) of the notification, in a standard notification
NotificationCompat.Builder setContentTitle (CharSequence title) : Sets the text (first row) of the notification, in a standard notification
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)
NotificationCompat.Builder setLargeIcon (Bitmap icon) : Sets the large icon that is shown in the ticker and notification
NotificationCompat.Builder setNumber (int number) : Sets the large number at the right-hand side of the notification
NotificationCompat.Builder setOngoing (boolean ongoing) : Sets whether this is an ongoing notification
NotificationCompat.Builder setSmallIcon (int icon) : Sets the small icon to use in the notification layouts
NotificationCompat.Builder setStyle (NotificationCompat.Style style) : Adds a rich notification style to be applied at build time
NotificationCompat.Builder setTicker (CharSequence tickerText) : Sets the text that is displayed in the status bar when the notification first arrives
NotificationCompat.Builder setVibrate (long[] pattern) : Sets the vibration pattern to use
NotificationCompat.Builder setWhen (long when) : Sets the time that the event occurred. Notifications in the panel are sorted by this time
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.
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.
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. 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.
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.
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