Android Custom Notification Example

Notification is a message that can be displayed outside the normal user interface of an android application. When the notification is issued, it first appears in the notification area of the status bar. Then users can click it to see the notification details.

1. Send Android Notification Steps.

  1. Call getSystemService(Context.NOTIFICATION_SERVICE) method to get NotificationManager instance.
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  2. Create A Notification object.
  3. Set Notification object’s various properties.
  4. Use NotificationManager to send the Notification.

2. Notification Properties And Methods.

  1. Notification.flags:
    Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_INSISTENT | Notification.FLAG_ONGOING_EVENT | Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_NO_CLEAR  | Notification.FLAG_AUTO_CANCEL | Notification.FLAG_FOREGROUND_SERVICE
  2. NotificationCompat.Builder.setDefaults(int defaults) :
    Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND | Notification.DEFAULT_ALL
  3. NotificationCompat.Builder.setVibrate(long[] pattern) : Set vibrate delayed time.
    NotificationCompat.Builder.setVibrate(new long[] {0,200,300,500});
    Effect: delay 0ms, then vibrate 300ms, delay 500ms, then vibrate 700ms.
  4. .setLights(int ledARGB ,int ledOnMS ,int ledOffMS )
    ledARGB means the lighting color, ledOnMS bright duration, ledOffMS dark time.
    This function is supported only when Flags are set to Notification.FLAG_SHOW_LIGHTS
  5. .setSound(Uri sound)
    Set default or custom reminder tones.
    .setSound(Uri.parse(“file:///sdcard/abc.mp3”))
  6. .setPriority(int pri) : Set Notification property.
    Notification.PRIORITY_MAX, Notification.PRIORITY_MIN, Notification.PRIORITY_HIGH, Notification.PRIORITY_LOW, Notification.PRIORITY_DEFAULT.

3. Android Notification Examples.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/rHQFnWLVsRU

This example includes five different notification types.

  1. Normal size notification.
    normal-screen-size-android-notification
  2. Large size notification.
    large-screen-size-android-notification
  3. Progress bar notification.
    progress-bar-android-notification
  4. Heads-up notification.
    heads-up-android-notification
  5. Custom view notification.
    custom-view-android-notification

4. Main Layout Xml File.

  1. activity_notification.xml
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <Button
            android:id="@+id/sendNormalSizeNotificationButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Send Normal Size Notification"
            android:textSize="20dp" />
    
        <Button
            android:id="@+id/sendLargeSizeNotificationButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Send Large Size Notification"
            android:textSize="20dp" />
    
        <Button
            android:id="@+id/sendProgressBarNotificationButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Send Progress Bar Notification"
            android:textSize="20dp" />
    
        <Button
            android:id="@+id/sendHeadsUpNotificationButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Send Heads-up Notification"
            android:textSize="20dp" />
    
        <Button
            android:id="@+id/sendCustomViewNotificationButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Send Custom View Notification"
            android:textSize="20dp" />
    
        <Button
            android:id="@+id/deleteProgressBarNotificationButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Delete Progress Bar Notification"
            android:textSize="20dp" />
    
        <Button
            android:id="@+id/deleteAllNotificationButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Delete All Notification"
            android:textSize="20dp" />
    
    </LinearLayout>

5. Activity Java File.

  1. This java file includes methods that will open different types of notifications.
  2. NotificationActivity.java
    package com.dev2qa.example;
    
    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.drawable.BitmapDrawable;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.app.NotificationCompat;
    import android.view.View;
    import android.widget.Button;
    import android.widget.RemoteViews;
    
    
    public class NotificationActivity extends AppCompatActivity {
    
    
        // Constants variable value that is used to identify different notification.
        private int NOTIFICATION_ID_NORMAL_SIZE = 1;
    
        private int NOTIFICATION_ID_LARGE_SIZE = 2;
    
        private int NOTIFICATION_ID_PROGRESS_BAR = 3;
    
        private int NOTIFICATION_ID_HEADS_UP = 4;
    
        private int NOTIFICATION_ID_CUSTOM_VIEW = 5;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_notification);
    
            setTitle("dev2qa.com --- Android Notification Example");
    
            this.sendNormalSizeNotification();
    
            this.sendLargeSizeNotification();
    
            this.sendProgressBarNotification();
    
            this.sendHeadsUpNotification();
    
            this.sendCustomViewNotification();
    
            this.deleteProgressBarNotification();
    
            this.deleteAllNotification();
        }
    
        // Click a button to show a normal screen size notification.
        private void sendNormalSizeNotification()
        {
            Button sendNormalSizeNotificationButton = (Button)findViewById(R.id.sendNormalSizeNotificationButton);
            sendNormalSizeNotificationButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    
                    // Create NotificationManager.
                    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
                    // NotificationTargetActivity is the activity opened when user click notification.
                    Intent intent = new Intent(NotificationActivity.this, NotificationTargetActivity.class);
                    Intent intentArr[] = {intent};
    
                    PendingIntent pendingIntent = PendingIntent.getActivities(NotificationActivity.this, 0, intentArr, 0);
    
                    // Create a Notification Builder instance.
                    String title = "Normal Size Happy Christmas. ";
                    String textContent = "Christmas is comming --- dev2qa.com";
                    int smallIconResId = R.drawable.message_block;
                    int largeIconResId = R.drawable.if_candy_cane;
                    long sendTime = System.currentTimeMillis();
                    boolean autoCancel = false;
    
                    // Get general settings Builder instance.
                    NotificationCompat.Builder builder = getGeneralNotificationBuilder(title, textContent, smallIconResId, largeIconResId, autoCancel, sendTime);
    
                    // Set content intent.
                    builder.setContentIntent(pendingIntent);
    
                    // Use both light, sound and vibrate.
                    builder.setDefaults(Notification.DEFAULT_ALL);
    
                    // Create Notification instance.
                    Notification notification = builder.build();
                    notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_INSISTENT;
    
                    // Send the notification.
                    notificationManager.notify(NOTIFICATION_ID_NORMAL_SIZE, notification);
                }
            });
        }
    
        // Click button to show a large screen size notification.
        private void sendLargeSizeNotification()
        {
            Button sendLargeSizeNotificationButton = (Button)findViewById(R.id.sendLargeSizeNotificationButton);
            sendLargeSizeNotificationButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    
                    // Create NotificationManager.
                    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
                    // NotificationTargetActivity is the activity opened when user click notification.
                    Intent intent = new Intent(NotificationActivity.this, NotificationTargetActivity.class);
                    Intent intentArr[] = {intent};
    
                    PendingIntent pendingIntent = PendingIntent.getActivities(NotificationActivity.this, 0, intentArr, 0);
    
                    // Create a Notification Builder instance.
                    String title = "Large Size Happy Christmas. ";
                    String textContent = "Christmas is comming --- dev2qa.com";
                    int smallIconResId = R.drawable.message_bookmark;
                    int largeIconResId = R.drawable.if_present;
                    long sendTime = System.currentTimeMillis();
                    boolean autoCancel = false;
    
                    // Get general settings Builder instance.
                    NotificationCompat.Builder builder = getGeneralNotificationBuilder(title, textContent, smallIconResId, largeIconResId, autoCancel, sendTime);
    
                    // Create a BigTextStyle object.
                    NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
                    bigTextStyle.bigText("Hello, this is the large screen size notification example");
                    bigTextStyle.setBigContentTitle("Happy Christmas Detail Info.");
                    // Set big text style.
                    builder.setStyle(bigTextStyle);
    
                    // Set content intent.
                    builder.setContentIntent(pendingIntent);
    
                    // Use both light, sound and vibrate.
                    builder.setDefaults(Notification.DEFAULT_ALL);
    
                    // Create Notification instance.
                    Notification notification = builder.build();
                    notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_INSISTENT;
    
                    // Send the notification.
                    notificationManager.notify(NOTIFICATION_ID_LARGE_SIZE, notification);
                }
            });
        }
    
        // Click button to show a progress bar notification.
        private void sendProgressBarNotification()
        {
            Button sendProgressBarNotificationButton = (Button)findViewById(R.id.sendProgressBarNotificationButton);
            sendProgressBarNotificationButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    
                    // Create NotificationManager.
                    final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
                    // NotificationTargetActivity is the activity opened when user click notification.
                    Intent intent = new Intent(NotificationActivity.this, NotificationTargetActivity.class);
                    Intent intentArr[] = {intent};
    
                    PendingIntent pendingIntent = PendingIntent.getActivities(NotificationActivity.this, 0, intentArr, 0);
    
                    // Create a Notification Builder instance.
                    String title = "Movie Download. ";
                    String textContent = "Download progress...";
                    int smallIconResId = R.drawable.message_delete;
                    int largeIconResId = R.drawable.if_reindeer;
                    long sendTime = System.currentTimeMillis();
                    boolean autoCancel = false;
    
                    // Get general settings Builder instance.
                    final NotificationCompat.Builder builder = getGeneralNotificationBuilder(title, textContent, smallIconResId, largeIconResId, autoCancel, sendTime);
    
                    // Set content intent.
                    builder.setContentIntent(pendingIntent);
    
                    // Use both light, sound and vibrate.
                    builder.setDefaults(Notification.DEFAULT_ALL);
    
                    // The thread object will update the Notification progress programmatically.
                    Thread updateProgressThread = new Thread(){
                        @Override
                        public void run() {
                            // Update the progress bar each second.
                            for (int i = 0; i <= 10; i++) {
                                //.builder.setProgress(10, i, true) will show a indeterminate progress bar.
                                builder.setProgress(10, i, false);
                                // Create Notification instance.
                                final Notification notification = builder.build();
                                notification.flags = Notification.FLAG_ONLY_ALERT_ONCE;
    
                                notificationManager.notify(NOTIFICATION_ID_PROGRESS_BAR, notification);
                                try {
                                    // Sleep for 1 seconds
                                    Thread.sleep(1*1000);
                                } catch (InterruptedException ex) {
                                    ex.printStackTrace();
                                }
                            }
                            builder.setContentText("Download complete");
                            //.builder.setProgress(0, 0, true) will show a indeterminate progress bar.
                            builder.setProgress(0,0,false);
                            // Send the notification.
                            // Create Notification instance.
                            final Notification notification = builder.build();
                            notification.flags = Notification.FLAG_ONLY_ALERT_ONCE;
                            notificationManager.notify(NOTIFICATION_ID_PROGRESS_BAR, notification);
                        }
                    };
    
                    // Start the thread.
                    updateProgressThread.start();
                }
            });
        }
    
        // Click button to show a Heads-up notification.
        private void sendHeadsUpNotification()
        {
            Button sendHeadsUpNotificationButton = (Button)findViewById(R.id.sendHeadsUpNotificationButton);
            sendHeadsUpNotificationButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    
                    // Create NotificationManager
                    final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
                    // NotificationTargetActivity is the activity opened when user click notification.
                    Intent intent = new Intent(NotificationActivity.this, NotificationTargetActivity.class);
                    Intent intentArr[] = {intent};
    
                    PendingIntent pendingIntent = PendingIntent.getActivities(NotificationActivity.this, 0, intentArr, 0);
    
                    // Create a Notification Builder instance.
                    String title = "Happy Christmas Heads Up!!!. ";
                    String textContent = "Jingle bells, jingle bells Jingle all the way Oh what fun it is to ride in a one horse open sleigh, hey.";
                    int smallIconResId = R.drawable.message_new;
                    int largeIconResId = R.drawable.if_santa;
                    long sendTime = System.currentTimeMillis();
                    boolean autoCancel = false;
    
                    // Get general settings Builder instance.
                    final NotificationCompat.Builder builder = getGeneralNotificationBuilder(title, textContent, smallIconResId, largeIconResId, autoCancel, sendTime);
    
                    // Use both light, sound and vibrate.
                    builder.setDefaults(Notification.DEFAULT_ALL);
    
                    // Set a heads-up notification.
                    builder.setFullScreenIntent(pendingIntent, true);
    
                    // Create Notification instance.
                    Notification notification = builder.build();
                    notificationManager.notify(NOTIFICATION_ID_HEADS_UP, notification);
                }
            });
        }
    
        // Click button to show a custom view notification.
        private void sendCustomViewNotification()
        {
            Button sendCustomViewNotificationButton = (Button)findViewById(R.id.sendCustomViewNotificationButton);
            sendCustomViewNotificationButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    
                    // Create NotificationManager
                    final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
                    // NotificationTargetActivity is the activity opened when user click notification.
                    Intent intent = new Intent(NotificationActivity.this, NotificationTargetActivity.class);
                    Intent intentArr[] = {intent};
    
                    PendingIntent pendingIntent = PendingIntent.getActivities(NotificationActivity.this, 0, intentArr, 0);
    
                    // Create a new Notification instance.
                    Notification notification = new Notification();
    
                    // Set small icon.
                    notification.icon = R.drawable.message_settings;
    
                    // Set large icon.
                    BitmapDrawable bitmapDrawable = (BitmapDrawable)getDrawable(R.drawable.if_snowflake);
                    Bitmap largeIconBitmap = bitmapDrawable.getBitmap();
                    notification.largeIcon = largeIconBitmap;
    
                    // Set flags.
                    notification.flags = Notification.FLAG_ONGOING_EVENT;
    
                    // Set send time.
                    notification.when = System.currentTimeMillis();
    
                    // Create and set notification content view.
                    RemoteViews customRemoteViews = new RemoteViews(getPackageName(), R.layout.activity_notification_custom_view);
                    notification.contentView = customRemoteViews;
    
                    // Set notification intent.
                    notification.contentIntent = pendingIntent;
    
                    notificationManager.notify(NOTIFICATION_ID_CUSTOM_VIEW, notification);
                }
            });
        }
    
        // This method create and return a general Notification Builder instance.
        private NotificationCompat.Builder getGeneralNotificationBuilder(String title, String textContent, int smallIconResId, int largeIconResId, boolean autoCancel, long sendTime)
        {
                // Create a Notification Builder instance.
                NotificationCompat.Builder builder = new NotificationCompat.Builder(NotificationActivity.this);
    
                // Set small icon.
                builder.setSmallIcon(smallIconResId);
    
                // Set large icon.
                BitmapDrawable bitmapDrawable = (BitmapDrawable)getDrawable(largeIconResId);
                Bitmap largeIconBitmap = bitmapDrawable.getBitmap();
                builder.setLargeIcon(largeIconBitmap);
    
                // Set title.
                builder.setContentTitle(title);
    
                // Set content text.
                builder.setContentText(textContent);
    
                // Set notification send time.
                builder.setWhen(sendTime);
    
                // If true then cancel the notification automatically.
                builder.setAutoCancel(autoCancel);
    
                return builder;
        }
    
        // Delete the ProgressBar notification.
        private void deleteProgressBarNotification()
        {
            Button deleteProgressBarNotificationButton = (Button)findViewById(R.id.deleteProgressBarNotificationButton);
            deleteProgressBarNotificationButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Create NotificationManager
                    final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    notificationManager.cancel(NOTIFICATION_ID_PROGRESS_BAR);
                }
            });
        }
    
        // Delete all notification.
        private void deleteAllNotification()
        {
            Button deleteAllNotificationButton = (Button)findViewById(R.id.deleteAllNotificationButton);
            deleteAllNotificationButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Create NotificationManager
                    final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    notificationManager.cancelAll();
                }
            });
        }
    }

6. Target Activity Layout Xml File.

  1. When the user clicks the notification content, it will open the target activity, the below file is just the target activity layout XML file.
  2. activity_notification_target.xml
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="10dp">
    
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/if_santa"
            android:layout_weight="1"/>
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Welcom to Happy Christmas application!"
            android:layout_weight="2"
            android:layout_gravity="center_vertical"
            android:textSize="20dp"/>
    
    </LinearLayout>

7. Target Activity Java File.

  1. NotificationTargetActivity.java
    package com.dev2qa.example;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    public class NotificationTargetActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_notification_target);
    
            setTitle("dev2qa.com --- Happy Christmas.");
        }
    }

8. Custom View Layout Xml File.

  1. This is a custom view layout XML file that the custom notification will use.
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/message_block"
            android:layout_gravity="center_vertical"/>
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is a custom notification."
            android:textSize="20dp"
            android:textColor="@color/colorOrange"
            android:layout_gravity="center_vertical"/>
    
    </LinearLayout>

2 thoughts on “Android Custom Notification Example”

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.