Android Notifications


Android Notfication Tutorial and Several Examples.

A notification is a message that android displays outside an app’s UI to provide reminders, communication with other people or timely information from your app.

Then when the user taps the notification, the app is opened or an action can be directly taken.

By using NotificationCompat APIs from the android support library we can create notifications all the way to Android 4.0 or API level 14.

The first step is to add the support library in app level build.gradle:

dependencies {
    implementation "com.android.support:support-compat:27.1.1"
}

In your java/kotlin code you will need to set the notification’s content and channel using the NotificationCompat.Builder object.

This example will create a notification with a small icon, title, and content.

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT);

Commonly Used APIs

Let's explore some of the commonly used API's when it comes to working with Notifications.

(a). Notification

Notification is a class that represents how a persistent notification is to be presented to the user using the NotificationManager.

(b). NotificationManager

NotificationManager is a class to notify the user of events that happen. This is how you tell the user that something has happened in the background.

(c) Intent

An intent is an abstract description of an operation to be performed. Read about Intents here.

(d). PendingIntent

A PendingIntent is a description of an Intent and target action to perform with it.

Normally instances of this class are created with:

  1. getActivity(Context, int, Intent, int) 2.getActivities(Context, int, Intent[], int).
  2. getBroadcast(Context, int, Intent, int), and
  3. getService(Context, int, Intent, int).

Two Notification Questions

In which Formats does a Notification Appear on a Device?

Well Notifications can appear in a device in different formats.

These formats include:

  1. An icon in the status bar.
  2. A more detailed entry in the notification drawer.
  3. As a badge on the app's icon.
  4. On paired wearables automatically.

Where does a Notification Appear on a Device?

Furthermore notifications can appear on a device in different locations.

These include:

(a). Status bar and notification drawer

It is the status bar where a notification first appears as an icon in the status bar when you issue a notification.

Users can then can swipe down on the status bar to open the notification drawer, where they can view more details and take actions with the notification.

Users can then drag down on a notification in the drawer to reveal the expanded view, which will show additional content and action buttons, if provided.

A notification will remain visible in the notification drawer until dismissed by the app or the user.

(b). Heads-up notification

Heads-up Notification is when a notification briefly appears in a floating window.

Android Heads up Notification

This features requires a minimum of Android 5.0.

Heads-up Notifications can be vital if you have a notification that your user should know about immediately.

They appear only if the device is unlocked.

They will appear the moment your app issues the notification and then disappear a moment afterwards. However they remain visible in the notification drawer as usual.

(c). Lock screen

Notifications can also appear on a locked screen if you want so.

Android Locked Screen Notification

This also requires Android 5.0.

The level of detail visible can be programmatically manipulated.

Then your users can use the system settings to choose the level of detail visible in lock screen notifications, including the option to disable all lock screen notifications.

Starting with Android 8.0, users can choose to disable or enable lock screen notifications for each notification channel.

Find more info here.

(d). App icon badge

Android 8.0 (API level 26) devices app icons can show a new notifications with a colored "badge" (also known as a "notification dot") on the corresponding app launcher icon. as a "notification dot") on the corresponding app launcher icon.

Android App Icon Notification

This allows your users to long-click on an app icon to see the notifications for that app.

They can also dismiss or act on notifications from that menu, similar to the notification drawer.

Examples

Android Notification Example - Open Activity when Notification is Clicked

Let's now look at a simple Notification example in Java.

This example will do the following for us:

  1. Show a Flaoting Action Button that when clicked will show a status bar notification.
  2. When the user clicks the Notification, we will bring up a new activity where we will be receiving a Notification ID.
  3. We will vibrate the device when the notification is displayed.

Suggest us by email or comment form an android example we add here.

MainActivity

  • MainActivity class.
  • Create and show Notification with alarm sound as well.
  • Increment messageCount.
  • When notifictaion is clicked open new activity
package com.tutorials.hp.hellonotifications;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.NotificationCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private int messageCount = 0;
    private static Uri alarmSound;
    // Vibration pattern long array
    private final long[] pattern = { 100, 300, 300, 300 };
    private NotificationManager mNotificationManager;

    /*
    - When activity is created.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // DEFAULT ALARM SOUND
        alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        // INITIALIZE NOTIFICATION MANAGER
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showNotification();
            }
        });
    }
    /*
    - Create Notification
    - Show Notification
     */
    protected void showNotification() {
        Log.i("Start", "notification");

        // Invoking the default notification service
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this);

        mBuilder.setContentTitle("ProgrammingWizards TV");
        mBuilder.setContentText("We've just released a new android video at our channel");
        mBuilder.setTicker("New Message Alert!");
        mBuilder.setSmallIcon(R.drawable.series);

        //Increment message count when a new message arrives
        mBuilder.setNumber(++messageCount);
        mBuilder.setSound(alarmSound);
        mBuilder.setVibrate(pattern);

        // Explicit intent to open notifactivity
        Intent i = new Intent(MainActivity.this,NotifActivity.class);
        i.putExtra("notificationId", 111);
        i.putExtra("message", "http://www.devosha.com");

        // Task builder to maintain task for pending intent
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(NotifActivity.class);

        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(i);

        //PASS REQUEST CODE AND FLAG
        PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);

        // notificationID allows you to update the notification later on.
        mNotificationManager.notify(111, mBuilder.build());
    }
    //end
}

NotifActivity

Here are our NotifActivity.java file.

  • Our NotifActivity class.
  • Opened when notification message is clicked.
  • Receives notifictaion id as well as message and displays in a textview.
  • Then clears the statusbar of the notification once its read
package com.tutorials.hp.hellonotifications;

import android.app.NotificationManager;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.util.Linkify;
import android.widget.TextView;

public class NotifActivity extends AppCompatActivity {
    /*
    - Set received notification to textview.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notif);

        TextView receivedTxt = (TextView) findViewById(R.id.notificationTxt);
        receivedTxt.setText(receiveData());
        Linkify.addLinks(receivedTxt, Linkify.ALL);
    }
    /*
    - Receive intent data and return
    - Then clear notification it from statusbar
     */
    private String receiveData()
    {
        String message = "";
        int id = 0;

        Bundle extras = getIntent().getExtras();// get intent data
        if (extras == null) {
            // If it is null then show error
            message = "Error";
        } else {
            // get id and message
            id = extras.getInt("notificationId");
            message = extras.getString("message");
        }
        message = "Notification Id : " + id + "n Message : " + message;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // remove the notification with the specific id
        mNotificationManager.cancel(id);

        return message;
    }
}

Here is our activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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="com.tutorials.hp.hellonotifications.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

Here is our content_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
    android:background="#fff"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.tutorials.hp.hellonotifications.MainActivity"
    tools:showIn="@layout/activity_main">

</android.support.constraint.ConstraintLayout>

Here is our activity_notif.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:background="#fff"
    android:layout_height="match_parent"
    tools:context="com.tutorials.hp.hellonotifications.NotifActivity">

    <TextView
        android:id="@+id/notificationTxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="5dp"
        android:textColor="#000000"
        android:textSize="20sp" />

</android.support.constraint.ConstraintLayout>

Here are our dependencies in our app level build.gradle file.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.+'
    implementation 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    implementation 'com.android.support:design:26.+'
}

Suggest us a video tutorial or preview for notifications we post here.

Android Notification examples

1. Create Notification

We see two ways of creating notifications, that targeting android N and above and that targeting below android N.

Here's the full code:

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.annotation.IdRes;
import android.view.View;
import android.widget.RemoteViews;

public class KNotification {

  private static NotificationManager sManager;

  static {
    sManager = (NotificationManager) getApplicationContext()
        .getSystemService(Context.NOTIFICATION_SERVICE);
  }

  public static void createNotification(Context context,@DrawableRes int smallIconID,  String title, String content, Intent intent){
    PendingIntent pendingIntent = PendingIntent.getActivity(context,1111,intent,PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = new Notification.Builder(context)
        .setContentTitle(title)
        .setContentText(content)
        .setSmallIcon(smallIconID)
        .setAutoCancel(true)
        .setContentIntent(pendingIntent)
        .build();

    sManager.notify(0,notification);
  }
    @TargetApi(Build.VERSION_CODES.N)
  public static void createNotification(Context context,@DrawableRes int smallIconID,RemoteViews bigView,Intent intent){
    PendingIntent pendingIntent = PendingIntent.getActivity(context,1111,intent,PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = new Notification.Builder(context)
        .setSmallIcon(smallIconID)
        .setAutoCancel(true)
        .setContentIntent(pendingIntent)
        .setCustomBigContentView(bigView)
        .build();

    sManager.notify(0,notification);
  }

}
2. How to Play Notification Sound

In this snippet we want to see how to play notification sound using the MediaPlayer class.

    static MediaPlayer mediaPlayer = null;
    public static void playNotifycationMusic (Context context ,String voicePath) throws IOException  {
        //paly music ...
        AssetFileDescriptor fileDescriptor = context.getAssets().openFd(voicePath);
        if(mediaPlayer == null ) {
            mediaPlayer = new MediaPlayer();
        }
        if(mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.reset();
        mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),fileDescriptor.getStartOffset(),
                fileDescriptor.getLength());
        mediaPlayer.prepare();
        mediaPlayer.setLooping(false);
        mediaPlayer.start();
    }
3. How to Create NotificationChannel, Send Notification

We are going to create a Notificaion utility class that will allow us:

  1. Create a NotificationChannel.
  2. Send Notifications.
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.v4.app.NotificationCompat;

public class NotificationUtil extends ContextWrapper {

    public static int NotificationID = 0 ;     

    private NotificationManager manager;
    public static final String nId = "download_channel";
    public static final String nName = "channel_name_1";

    public NotificationUtil ( Context base ) { super ( base ); }   

    public void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel channel = new NotificationChannel(nId, nName,
                    NotificationManager.IMPORTANCE_MIN);
            getManager().createNotificationChannel(channel);
        }
    }

    public NotificationManager getManager() {
        if (manager == null) {
            manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        }
        return manager;
    }

    public Notification.Builder getChannelNotification(String title, int progress) {
        if (Build.VERSION.SDK_INT >= 26) {
            Notification.Builder builder = new Notification.Builder(getApplicationContext(), nId);
            builder.setContentTitle(title);
            builder.setSmallIcon(R.drawable.ic_stat_kangaroo);
            if (progress > 0) {
                builder.setContentText(progress + "%");
                builder.setProgress(100, progress, false);
            }
            return builder;
        }
        return null;
    }

    public Notification.Builder getChannelNotification(String title, String content) {
        if (Build.VERSION.SDK_INT >= 26) {
            Notification.Builder builder = new Notification.Builder(getApplicationContext(), nId);
            builder.setContentTitle(title);
            builder.setContentText(content);
            builder.setSmallIcon(R.drawable.ic_stat_kangaroo);
            builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
            builder.setAutoCancel(true);
            builder.setPriority(Notification.PRIORITY_MAX);
            return builder;
        }
        return null;
    }

    public NotificationCompat.Builder getNotificationBuilder(String title, int progress) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                getApplicationContext());
        builder.setContentTitle(title);
        builder.setSmallIcon(R.drawable.ic_stat_kangaroo);
        if (progress > 0) {
            builder.setContentText(progress + "%");
            builder.setProgress(100, progress, false);
        }
        return builder;
    }

    public NotificationCompat.Builder getNotificationBuilder(String title, String content) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                getApplicationContext());
        builder.setContentText(content);
        builder.setContentTitle(title);
        builder.setSmallIcon(R.drawable.ic_stat_kangaroo);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setAutoCancel(true);
        return builder;
    }

    public void sendNotification(String title, int progress) {
        if (Build.VERSION.SDK_INT >= 26) {
            createNotificationChannel();
            Notification notification = getChannelNotification(title, progress)
                    .build();
            getManager().notify(-1, notification);
        } else {
            Notification notification = getNotificationBuilder(title, progress).build();
            getManager().notify(-1, notification);
        }
    }

    public void sendNotification(String title, String content) {
        if (Build.VERSION.SDK_INT >= 26) {
            createNotificationChannel();
            Notification notification = getChannelNotification(title, content)
                    .build();
            getManager().notify(NotificationID++, notification);
        } else {
            Notification notification = getNotificationBuilder(title, content).build();
            getManager().notify(NotificationID++, notification);
        }
    }

}

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post