Create Notification

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.


Here are the most important parts of a notification:

  • Small Icon: required and set with setSmallIcon()
  • Large Icon: optional and set with setLargeIcon()
  • Title: optional and set with setContentTitle()
  • Text: optional and set with setContentText()
  • App name: provided by the system
  • Time stamp: provided by the system but can be overriden with setWhen()

So don't waste more time, let's start create notification, following code snippet will tell you how to create notification:

MainActivity.java
package com.theitbulls.notificationex;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

public class MainActivity extends AppCompatActivity {
    private static final String CHANNEL_ID = "NOTIFICATION_CHANNEL";
    private static final int NOTIFICATION_ID = 0x352;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
    }

    public void show(View view) {
        Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.small_logo);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Demo Notificaiton")
                .setContentText("This is notification demo here.")
                .setSmallIcon(R.drawable.small_logo)
                .setLargeIcon(largeIcon)
                .setAutoCancel(false)
                .setWhen(100);

        NotificationManagerCompat mgr = NotificationManagerCompat.from(this);
        mgr.notify(NOTIFICATION_ID, builder.build());

    }
}


See the result of above code snippet:


Attach Action to Notification:

This is an optional part and required if you want to attach an action with the notification. An action allows users to go directly from the notification to an Activity in your application, where they can look at one or more events or do further work.

The action is defined by a PendingIntent containing an Intent that starts an Activity in your application. To associate the PendingIntent with a gesture, call the appropriate method of NotificationCompat.Builder. For example, if you want to start Activity when the user clicks the notification text in the notification drawer, you add the PendingIntent by calling setContentIntent().

package com.theitbulls.notificationex;

import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.app.TaskStackBuilder;

public class MainActivity extends AppCompatActivity {
    private static final String CHANNEL_ID = "NOTIFICATION_CHANNEL";
    private static final int NOTIFICATION_ID = 0x352;
    private static final int REQ_CODE = 0x542;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
    }

    public void show(View view) {
        Intent notificationIntent = new Intent();
        notificationIntent.setClass(this, NotificationActivity.class);

        Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.small_logo);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Demo Notificaiton")
                .setContentText("This is notification demo here.")
                .setSmallIcon(R.drawable.small_logo)
                .setLargeIcon(largeIcon)
                .setAutoCancel(false)
                .setWhen(100);

        // open activity on click of notification
        Intent resultIntent = new Intent(this, NotificationActivity.class);

        // use TaskStackBuilder to start activity
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);

        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(REQ_CODE, PendingIntent.FLAG_UPDATE_CURRENT);

        // add pending intent to notification builder
        builder.setContentIntent(resultPendingIntent);

        NotificationManagerCompat mgr = NotificationManagerCompat.from(this);
        mgr.notify(NOTIFICATION_ID, builder.build());

    }
}


Result of above code snippet:



Custom Notification:

We will create a project where we create custom notification using setCustomBigContentView() and setCustomContentView(). CustomBigContentView will use to show notification when we expand notification and CustomContentView will use to show shrieked notification. Let's create example first we create notification_collapse.xml and notification_expandable.xml one by one.

First create notification_collapse.xml as:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="8dp">

    <ImageButton
        android:id="@+id/imgBtnEdit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/imgBtnDelete"
        android:src="@android:drawable/ic_menu_edit" />

    <ImageButton
        android:id="@+id/imgBtnDelete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:src="@android:drawable/ic_menu_delete" />

    <ImageView
        android:id="@+id/small_icon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:paddingLeft="4dp"
        android:paddingRight="6dp"
        android:paddingBottom="1dp"
        android:src="@drawable/small_logo" />

    <TextView
        android:id="@+id/content_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@+id/small_icon"
        android:text="Notification Sample App"
        android:textAppearance="@style/TextAppearance.Compat.Notification.Title" />

</RelativeLayout>

Now create notification_expandable.xml as:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="8dp">

    <LinearLayout
        android:id="@+id/notification_main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="3dp"
        android:layout_alignParentTop="true"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:paddingLeft="6dp">

        <TextView
            android:id="@+id/content_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Notification Sample App"
            android:textAppearance="@style/TextAppearance.Compat.Notification.Info" />

        <TextView
            android:id="@+id/content_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Expand me to see a detailed message!"
            android:textAppearance="@style/TextAppearance.Compat.Notification" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/notification_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/notification_main"
        android:layout_marginTop="8dp"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/big_icon"
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:adjustViewBounds="true"
            android:src="@drawable/it_bulls_logo" />

        <TextView
            android:id="@+id/notification_message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:textSize="9pt"
            android:maxLines="8"
            android:text="@string/remote_view_msg"
            android:textAppearance="@style/TextAppearance.Compat.Notification.Info" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/notification_info"
        android:layout_alignParentRight="true">

        <ImageButton
            android:id="@+id/imgBtnEdit"
            style="@style/Widget.Compat.NotificationActionContainer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_menu_edit"

            android:text="CLICK ME" />

        <ImageButton
            android:id="@+id/imgBtnDelete"
            style="@style/Widget.Compat.NotificationActionContainer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_menu_delete"
            android:text="CLICK ME" />
    </LinearLayout>

    <TextView
        android:id="@+id/timestamp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:paddingTop="8dp"
        android:paddingRight="3.5dp"
        android:textAppearance="@style/TextAppearance.Compat.Notification.Time" />

</RelativeLayout>

Note: As we says always use androidx components, when we use in these layout file we got exception so we don't use androix components in these layout files.


Now we create MainActivity.java as:

package com.theitbulls.notificationex;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.RemoteViews;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.app.TaskStackBuilder;

public class MainActivity extends AppCompatActivity {
    public static final String NOTIFY_EDIT = "com.theitbulls.notificationex.EDIT";
    public static final String NOTIFY_DELETE = "com.theitbulls.notificationex.DELETE";

    public static final String CHANNEL_ID = "NOTIFICATION_CHANNEL";
    public static final int NOTIFICATION_ID = 0x352;
    private static final int REQ_CODE = 0x542;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
    }

    public void bigViewNotify(View view) {
        Intent intentNotif = new Intent(this, NotificationActivity.class);
        intentNotif.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intentNotif, PendingIntent.FLAG_UPDATE_CURRENT);

        RemoteViews collapseView = new RemoteViews(getPackageName(), R.layout.notification_collapse);
        RemoteViews expandView = new RemoteViews(getPackageName(), R.layout.notification_expandable);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setCustomBigContentView(expandView)
                .setCustomContentView(collapseView)
                .setContentTitle(getString(R.string.remote_view_title));


        Notification notification = builder.build();

        actionOnButton(collapseView);
        actionOnButton(expandView);

        collapseView.setImageViewResource(R.id.small_icon, R.drawable.small_logo);
        collapseView.setImageViewResource(R.id.imgBtnEdit, android.R.drawable.ic_menu_edit);
        collapseView.setImageViewResource(R.id.imgBtnDelete, android.R.drawable.ic_menu_delete);

        expandView.setImageViewResource(R.id.big_icon, R.drawable.it_bulls_logo);
        expandView.setTextViewText(R.id.timestamp, DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME));
        expandView.setTextViewText(R.id.notification_message, getString(R.string.remote_view_msg));
        expandView.setImageViewResource(R.id.imgBtnEdit, android.R.drawable.ic_menu_edit);
        expandView.setImageViewResource(R.id.imgBtnDelete, android.R.drawable.ic_menu_delete);

        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        NotificationManagerCompat mgr = NotificationManagerCompat.from(this);
        mgr.notify(NOTIFICATION_ID, notification);
    }

    private void actionOnButton(RemoteViews customView) {
        Intent editIntent = new Intent(NOTIFY_EDIT);
        Intent deleteIntent = new Intent(NOTIFY_DELETE);

        PendingIntent editPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), REQ_CODE, editIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        customView.setOnClickPendingIntent(R.id.imgBtnEdit, editPendingIntent);

        PendingIntent deletePendingIntent = PendingIntent.getBroadcast(getApplicationContext(), REQ_CODE, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        customView.setOnClickPendingIntent(R.id.imgBtnDelete, deletePendingIntent);
    }
}


For CustomNotification action we create a BroadCastReceiver name is ActionBroadCast.java as:

package com.theitbulls.notificationex;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import androidx.core.app.NotificationManagerCompat;

public class ActionBroadCast extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (MainActivity.NOTIFY_EDIT.equals(intent.getAction())) {
            NotificationManagerCompat mgr = NotificationManagerCompat.from(context);
            mgr.cancel(MainActivity.NOTIFICATION_ID);

            Toast.makeText(context, "Notification clicked for Edit.", Toast.LENGTH_SHORT).show();
        } else if (MainActivity.NOTIFY_DELETE.equals(intent.getAction())) {
            NotificationManagerCompat mgr = NotificationManagerCompat.from(context);
            mgr.cancel(MainActivity.NOTIFICATION_ID);

            Toast.makeText(context, "Notification clicked for Delete.", Toast.LENGTH_SHORT).show();
        }
    }
}



Download: Notification & Custom Notification Example Download Here