push notification in android example:
A notification is a message you can display to the user outside of your application's normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time.
Android provides NotificationManager class for this purpose. In order to use this class, you need to instantiate an object of this class by requesting the android system through getSystemService() method.>>>
As a first step is to create a notification builder using NotificationCompat.Builder.build(). You will use Notification Builder to set various Notification properties like its small and large icons, title, priority
To Create Notification :
To create notification we have to use NotificationCompat.Builder’s object. Notification itself build by NotificationCompat.Builder.build(), which returns a Notification object containing with specifications of notification.
A Notification object must contain setSmallIcon() to set a small icon, setContentTitle() to set title and setContentText() to set detailed text. Another settings and contents are optional.
To set action like as call another activity directly by clicking on the notification, we have to use PendingIntent with containing an Intent which starts an Activity of our application.
We show below different type of push notification :
Step-1: Create Receiver .java class it is extend with Broadcast Receivers :
package com.example.notificationtest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import androidx.core.app.NotificationManagerCompat;
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
//get notificationId of notification using intent
int id = intent.getIntExtra("id", 0);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
//cancel the specific notificationId notification.
notificationManagerCompat.cancel(id);
}
}
}
Step-2: Create Main Activity.Xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_simple_notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/padding_15dp"
android:text="@string/simple_notification_title"
android:textAllCaps="false"
android:textSize="@dimen/textsize_15sp"
app:layout_constraintBottom_toTopOf="@+id/btn_bigtextstyle_notification"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn_bigtextstyle_notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/padding_15dp"
android:text="@string/bigtext_notification_style_title"
android:textAllCaps="false"
android:textSize="@dimen/textsize_15sp"
app:layout_constraintBottom_toTopOf="@+id/btn_bigpicturestyle_notification"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_simple_notification" />
<Button
android:id="@+id/btn_bigpicturestyle_notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/padding_15dp"
android:text="@string/bigPicture_notification_style_title"
android:textAllCaps="false"
android:textSize="@dimen/textsize_15sp"
app:layout_constraintBottom_toTopOf="@+id/btn_inboxstyle_notification"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_bigtextstyle_notification" />
<Button
android:id="@+id/btn_inboxstyle_notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/padding_15dp"
android:text="@string/inbox_notification_style_title"
android:textAllCaps="false"
android:textSize="@dimen/textsize_15sp"
app:layout_constraintBottom_toTopOf="@+id/btn_action_notification"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_bigpicturestyle_notification" />
<Button
android:id="@+id/btn_action_notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/padding_15dp"
android:text="@string/action_notification_title"
android:textAllCaps="false"
android:textSize="@dimen/textsize_15sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_inboxstyle_notification" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step-3:Create Activity Main :
package com.example.notificationtest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
final String CHANNEL_ID = "Important_mail_channel";
Button mBtnSimpleNotification, mBtnBigTextNotification,
mBtnBigPictureNotification, mBtnInboxNotification, mBtnActionNotification;
NotificationManagerCompat mNotificationManagerCompat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannel();
mBtnSimpleNotification = findViewById(R.id.btn_simple_notification);
mBtnBigTextNotification = findViewById(R.id.btn_bigtextstyle_notification);
mBtnBigPictureNotification = findViewById(R.id.btn_bigpicturestyle_notification);
mBtnInboxNotification = findViewById(R.id.btn_inboxstyle_notification);
mBtnActionNotification = findViewById(R.id.btn_action_notification);
mBtnSimpleNotification.setOnClickListener(this);
mBtnBigTextNotification.setOnClickListener(this);
mBtnBigPictureNotification.setOnClickListener(this);
mBtnInboxNotification.setOnClickListener(this);
mBtnActionNotification.setOnClickListener(this);
mNotificationManagerCompat = NotificationManagerCompat.from(MainActivity.this);
}
@Override
public void onClick(View view) {
int viewId = view.getId();
switch (viewId) {
case (R.id.btn_simple_notification):
createSimpleNotification(getString(R.string.simple_notification_title),
getString(R.string.simple_notification_text), 1);
break;
case (R.id.btn_bigtextstyle_notification):
createBigTextNotification(getString(R.string.bigtext_notification_title),
getString(R.string.bigtext_notification_text), 2);
break;
case (R.id.btn_bigpicturestyle_notification):
createBigPictureNotification(getString(R.string.bigPicture_notification_title),
getString(R.string.bigPicture_notification_text), 3);
break;
case (R.id.btn_inboxstyle_notification):
createInboxNotification(getString(R.string.inbox_notification_title),
getString(R.string.inbox_notification_text), 4);
break;
case (R.id.btn_action_notification):
createActionNotification(getString(R.string.action_notification_title),
getString(R.string.action_notification_text), 5);
break;
}
}
// code for Creating simple notification :
private void createSimpleNotification(String title, String text, int notificationId) {
//removes all previously shown notifications.
mNotificationManagerCompat.cancelAll();
//Bitmap formats are best for images that need to have a wide range of color gradations, such as most photographs.
// Vector formats, on the other hand, are better for images that consist of a few areas of solid color.
// Examples of images that are well suited for the vector format include logos and type
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.nature_img);
//open the url when user taps the notification
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com /"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(text)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
//Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();
// notificationId is a unique int for each notification that you must define
mNotificationManagerCompat.notify(notificationId, notification);
}
//for Creating BiGtext Notification
private void createBigTextNotification(String title, String text, int notificationId) {
//removes all previously shown notifications.
mNotificationManagerCompat.cancelAll();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.nature_img);
NotificationCompat.BigTextStyle style = new NotificationCompat.
BigTextStyle().bigText(text + " used for generating large-format notifications that include a lot of text.")
//set different title in expanded mode.
.setBigContentTitle(null)
//needed if an app sends notification from multiple sources(accounts).
.setSummaryText("BigTextStyle");
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(text + " used for generating large-format notifications that include a lot of text.")
//set Big text template
.setStyle(style)
//Set the large icon in the notification.
.setLargeIcon(bitmap)
.build();
mNotificationManagerCompat.notify(notificationId, notification);
}
//For Creating BigPicture notification :
private void createBigPictureNotification(String title, String text, int notificationId) {
//removes all previously shown notifications.
mNotificationManagerCompat.cancelAll();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.nature_img);
NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle()
//set big picture
.bigPicture(bitmap)
//set the content text in expanded form.
.setSummaryText("BigPicture style is used to show large image.")
//set different title in expanded mode.
.setBigContentTitle(null)
//set different large icon in expanded mode.
.bigLargeIcon(null);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(text)
//Set the large icon in the notification.
.setLargeIcon(bitmap)
//set Big picture template
.setStyle(style)
.build();
mNotificationManagerCompat.notify(notificationId, notification);
}
private void createInboxNotification(String title, String text, int notificationId) {
//removes all previously shown notifications.
mNotificationManagerCompat.cancelAll();
String line1 = "This is line1 ";
String line2 = "This is line2 ";
String line3 = "This is line3 ";
String line4 = "This is line4 ";
String line5 = "This is line5 ";
String line6 = "This is line6 ";
String line7 = "This is line7 ";
NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle()
//To add n lines, call it n times
.addLine(line1)
.addLine(line2)
.addLine(line3)
.addLine(line4)
.addLine(line5)
.addLine(line6)
.addLine(line7)
//needed if an app sends notification from multiple sources(accounts).
.setSummaryText("InboxStyle")
//set different title in expanded mode.
.setBigContentTitle(null);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText("It is used for notifications includes a list of (up to 5) strings.")
//set inbox style in notification
.setStyle(style)
.build();
mNotificationManagerCompat.notify(notificationId, notification);
}
private void createActionNotification(String title, String text, int notificationId) {
//removes all previously shown notifications.
mNotificationManagerCompat.cancelAll();
Intent intent = new Intent(getApplicationContext(), Receiver.class);
intent.setAction("ACTION_CANCEL");
//passing notificationId to receiver class through intent
intent.putExtra("id", notificationId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//action fire on click of notification Dismiss action button.
NotificationCompat.Action actionDismiss =
new NotificationCompat.Action.Builder(0,
"Dismiss", pendingIntent)
.build();
//action fire on click of notification Delete action button.
NotificationCompat.Action actionDelete =
new NotificationCompat.Action.Builder(0,
"Delete", pendingIntent)
.build();
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(text)
.setStyle(new NotificationCompat.BigTextStyle().
bigText("This is an example of BigTextStyle notification with action."))
//Add actions Dismiss and Delete to this notification.
.addAction(actionDismiss)
.addAction(actionDelete)
.build();
mNotificationManagerCompat.notify(notificationId, notification);
}
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//Channel name
CharSequence name = "Important_mail_channel";
//Channel description
String description = "This channel will show notification only to important people";
//The importance level you assign to a channel applies to all notifications that you post to it.
int importance = NotificationManager.IMPORTANCE_DEFAULT;
//Create the NotificationChannel
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
//Set channel description
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this.
//Notification Manager. Android allows to put notification into the titlebar of your application. The user can expand
// the notification bar and by selecting the notification the user can trigger another activity.
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}