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:
PendingIntent.getActivity()
: Retrieve a PendingIntent to start an ActivityPendingIntent.getBroadcast()
: Retrieve a PendingIntent to perform a BroadcastPendingIntent.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 :
- this (context) : This is the context in which the PendingIntent starts the activity
- 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.
- intent : Explicit intent object of the activity to be launched
- 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.
- 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.
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
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.
References: