Twitter LogoFacebook Logo
Android Notifications with Firebase Cloud Messaging
Hello, in this tutorial, I will show you how to send and receive notifications in Android using Firebase Cloud Messaging.
By: King

Hello, in this tutorial, I will show you how to send and display notifications in Android using Firebase Cloud Messaging.

Setup

Before we begin, you’ll need to have a Google account. If you do not have one, go to accounts.google.com/signup to sign up for one. 

accounts.google.com/signup

You’ll also need to have a Firebase project. To create one, go to console.firebase.google.com, sign in with your Google account, and create a project.

console.firebase.google.com

Once you have your Firebase Project, click on the Android icon in the Project Overview page and add Firebase to your Android application.

Image from Codeible.com

For the package name, use the package name from your Main Activity file for your Android project. 

Image from Codeible.com

Then generate the SHA-1 certificate by going back to Android Studio. 

Click on the Gradle tab on the right. 

Expand the dropdown menu, go to app, Tasks, android, and then signingReport.

Image from Codeible.com

Copy the SHA-1 Certificate in the terminal and paste it inside the textbox in Firebase. 

Image from Codeible.com
Image from Codeible.com

Click on Register App to continue to the next step.

On Step-2, download the google-services.json file and find it. 

Go to your project on Android Studio and switch to the Project view.

Place the google-services.json file inside the app folder.

Image from Codeible.com

Go to the Firebase console and continue to step 3.

Copy the code in the dependencies section and add it to the dependencies section of your project’s build gradle file.

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.2"
        classpath 'com.google.gms:google-services:4.3.8'
    }
}

Go back to the Firebase console and scroll down.

Copy the apply plugin code and add it to your project’s app gradle file in Android Studio.

apply plugin: 'com.google.gms.google-services'

Continue by copying the dependencies code and add them to your app. 

dependencies {
    ...
    implementation platform('com.google.firebase:firebase-bom:28.0.1')
    implementation 'com.google.firebase:firebase-analytics'
}

Click on “Sync Now” and wait until the process is finished.

In the Firebase console, continue to the next step to complete the process.

Handling Notifications

Once the Firebase project is connected with the Android application, we can begin creating a service to handle our notifications.

Go to the app build gradle file. In the dependencies section, add the Firebase Cloud Messaging dependency and sync the project.

dependencies {
    ...
    implementation platform('com.google.firebase:firebase-bom:28.0.1')
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-messaging'
}

Create a new class call PushNotificationService and have it extend the FirebaseMessagingService class.

public class PushNotificationService extends FirebaseMessagingService {

}

Go to the manifest file and add the service to the app. 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.codeible.pushnotificationtutorial">

    <application
       ...>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service 
             android:name=".PushNotificationService" 
             android:exported="false">
            <intent-filter>
                <action 
                      android:name="com.google.firebase.MESSAGING_EVENT">
                 </action>
            </intent-filter>
        </service>
    </application>

</manifest>

This is all we need to do to start receiving notifications from Firebase. 

Sending Notifications using Firebase Cloud Messaging UI

Let’s see how we can send a notification. 


Run the app on the emulator and put it on the background. 

Go to the Firebase console. Under Engage, go to Cloud Messaging. 

Image from Codeible.com

We can use this tool to send out notifications to a specific group, device, or topic.


Click on Send your first message and enter a title and text for the notification.

Image from Codeible.com

Scroll down and click next to continue to the next step.

For step-2, we can chose who we want to send the notification to. We can send it to a specific app, or a specific topic.

For step-3, we can choose when to send the notification. Since we are testing, we want to send it now.

Steps-4 and 5 are optional so we can skip them.

Click Review and Publish to send the notification.

If we go to the emulator, a notification should appear in the status bar.

Modifying the Notification Behavior

By default, the notifications will only appear when the app is running in the background or if it is closed.

To change this behavior, go to the notification service class and override the onMessageReceived() method from the FirebaseMessagingService class. 

The method is called every time it receives a notification from Firebase. 

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
}

We can put our own notification code in here to change how the notification will appear.

The RemoteMessage object returned represents the notification message that was received. 

We can get the title of the notification by calling getNotification() and getTitle().

To get the notification text, call getBody().

String title = remoteMessage.getNotification().getTitle();
String text = remoteMessage.getNotification().getBody();

Displaying the Notification

Now, let’s add the code to display the notification. First we’ll need a notification channel. 

The purpose of the channel is to establish a link between our app and the Android Device.  We can use this channel to set the behavior of the notifications.

 NotificationChannel channel = new NotificationChannel();

It takes 3 parameters. 

The first parameter is the channel id. 
The second parameter is the name for the channel. 
The third parameter is the importance level. 

There are 4 importance levels: IMPORTANCE_HIGH, IMPORTANCE_DEAFULT, IMPORTANCE_LOW, and IMPORTANCE_MIN.


With IMPORTANCE_HIGH, it’ll make the notification appear as a pop-up, on top of our app which is what we want.

final String CHANNEL_ID = "HEADS_UP_NOTIFICATION";

NotificationChannel channel = new NotificationChannel(
        CHANNEL_ID,
        "Heads Up Notification",
        NotificationManager.IMPORTANCE_HIGH
);

Once we have our channel, we have to add the channel to the Android Device. Call getSystemService() and pass in the NotificationManager class. Then call createNotificationChannel() and pass in the channel.

getSystemService(NotificationManager.class)

.createNotificationChannel(channel);

Now that the app is linked with the device, we can create the notification object and display it.
Use the notification builder to create the notification.

Notification.Builder notification = new Notification.Builder(this, CHANNEL_ID)

Call setContentTitle() to set the title. 

Call setContentText() to set the text.
Call setSmallIcon() to provide a small icon for the notification.
Call setAutoCancel() to true to make the notification go away when we tap on it.

Notification.Builder notification =

  new Notification.Builder(this, CHANNEL_ID)
  .setContentTitle(title)
  .setContentText(text)
  .setSmallIcon(R.drawable.ic_launcher_background)
  .setAutoCancel(true);

The last step we need to do is to send the notification through the channel so it’ll get displayed. 

Grab the NotificationManagerCompat class and call the from() method. 
Pass in the context and then call the notify method.

It takes 2 parameters, the first parameter is the ID for the notification, and the second is the notification object that we want to send. 

NotificationManagerCompat.from(this).notify(1, notification.build());

Full Code

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

      String title = remoteMessage.getNotification().getTitle();
      String text = remoteMessage.getNotification().getBody();

      final String CHANNEL_ID "HEADS_UP_NOTIFICATION";

      NotificationChannel channel = new NotificationChannel(
           CHANNEL_ID,
           "Heads Up Notification",
           NotificationManager.IMPORTANCE_HIGH
      );

      Notification.Builder notification =
        new Notification.Builder(this, CHANNEL_ID)
        .setContentTitle(title)
        .setContentText(text)
        .setSmallIcon(R.drawable.ic_launcher_background)
        .setAutoCancel(true);

      NotificationManagerCompat.from(this).notify(1, notification.build());

      super.onMessageReceived(remoteMessage);
}

If we run the app and send a notification from the Firebase console, a Heads-Up notification will be displayed.


Sign In