Twitter LogoFacebook Logo
Automated Android Notifications with Firebase Cloud Functions, Messaging, and Firestore
Hello, in this video, I will show you how to send notifications automatically to users using Firebase Cloud Functions.
By: King

Source code download:

How it works

There are 2 ways that you can send notifications to an individual or a group of users using Firebase Cloud Messaging programmatically. 


The first method is to allow them to subscribe to a topic and then broadcast our notifications to subscribers of a topic or we can store the Registration Tokens from each user and then broadcast our notifications using their tokens.

Setup

Step 1

The first thing we need to have is a Firebase project that is linked with your Android application. 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. 

Image from Codeible.com

For the package name, use the package name from the MainActivity file of your application. 

Image from Codeible.com

Then generate a 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 signing report.

Image from Codeible.com

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

Image from Codeible.com

Click on Register App to continue to the next step.

Step 2

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 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 until you see the code to add more dependencies. Copy the apply plugin code and add it to the app’s build grade file in Android Studio

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

Continue by copying the dependencies code and add them to the 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.

Once the project is linked with the Android application, we can begin building the service to handle our notifications.

Building the Notification Service

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

dependencies {
    ...
    implementation 'com.google.firebase:firebase-messaging'
}

Once the process is finished create a new class call PushNotification Service and have it extend the FirebaseMessagingService class.

public class PushNotificationService extends FirebaseMessagingService {

}

Override the onMessageReceived() method from the FirebaseMessagingService Class. 


The method is called every time it receives a notification from Firebase. We can put our own notification code here to change how the notification will appear.

public class PushNotificationService extends FirebaseMessagingService {
  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
          super.onMessageReceived(remoteMessage);
  }
}

By default, a notification will only appear when the app is closed or in the background. To change this The RemoteMessage object 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();

Now let’s add the code to display the notification.

First we need to have a notification channel. The purpose of the channel is to establish a link between our app and the Android device.

NotificationChannel channel = new NotificationChannel();

It takes 3 parameters. 


The first parameter is the channel id. 
The second parameter is the name of the channel. 
And the third parameter is the IMPORTANCE LEVEL.

If we look at the Android Developer documentation, there are 4 importance levels: High, Default, Low, and Min. 


With IMPORTANCE_HIGH, it’ll make the notification appear as a popup. Go back to Android Studio and use IMPORTANCE_HIGH from NotificationManager.

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 need 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 Notificaton Builder to build the notification. 


Call setContentTitle() to set the title. 
Call setContentText() to set the text. 
Call setSmallIcon() to provide a small icon for the notification. 
And set auto cancel 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 display. 


Grab the NotificationManagerCompat class. 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());

Now that we have our notification service code set up to handle our incoming notifications, we need to add it inside the manifest file to activate it.

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

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

</manifest>

This is all we need to do to start receiving notifications from Firebase. Let’s see how we can add triggers in Cloud Functions to automatically fire and send notifications to users.

Automatic Notifications

Installing NodeJS & Firebase Tools

We’ll begin by creating a Cloud Functions project. Make sure you have NodeJS and firebase-tools installed on your computer. 


Run node -v to get  the version of node you have installed.

node-v

Run firebase - -version for firebase-tools

firebase - -version

If you do not have them installed, go to nodejs.org and follow the steps to install node. 


For firebase-tools, run npm install -g firebase-tools after you have node installed.

npm install -g firebase-tools

Creating a Firebase Cloud Functions Project

When you have verified that you have NodeJS and firebase-tools installed, create a folder where it is easy to locate. 


Open a terminal for that directory and log into firebase. Afterwards, initialize Firebase Cloud Functions using the firebase init command. 

firebase init

Select the Firebase project you have for the app and continue. 


Select “Yes” to the install dependencies question and continue.

Image from Codeible.com

Once Cloud Functions is set, open the project in a code editor. Expand the functions folder and go to the index.js file. In here, we can define our trigger functions. 

To define a function for Cloud Functions, grab the exports object and use the dot operator to add a name for the function. 


Take the functions object and get the Firestore module. To check if a document is added to a collection, call document() then onCreate(). 

exports.pushNotificationsToTutorialSubscribers = functions.firestore.document().onCreate(
    (snapshot, context) => {

    }
);

Inside the parenthesis of document(), pass in the location of where you want to detect. 


For example, if we have a collection call Notifications. The path we’ll use will be Notifications to represent the collection, and the document id to represent the document.

functions.firestore.document("Notifications/docId").onCreate(...)

However, instead of using a static value to represent a single document, wrap the document id with the curly brackets to represent any document. 

"Notifications/{docId}"

The onCreate() function represents the action we want to detect. Whenever a document is created on this path, we’ll run this block of code. This will be our trigger to send notifications to users.


To send a notification to users who subscribe to a topic, import firebase-admin and initialize the app. 

const functions = require("firebase-functions");
...
const admin = require('firebase-admin');
admin.initializeApp();

exports.pushNotificationsToTutorialSubscribers...

Inside trigger function, grab the admin object, get the messaging() module, and call the sendToTopic() function. 


It takes 2 parameters, the first is the topic we want to broadcast to, and the second is an object that contains the notification information. 

exports.pushNotificationsToTutorialSubscribers = functions.firestore.document().onCreate(
    (snapshot, context) => {
        return admin.messaging().sendToTopic(
            "new_user_forums",
            {
                notification: {
                    title: "A New Notification",
                    body: "Hello World!"
                }
            }
        );
    }
);

The next thing we need to do is to deploy this function to cloud functions to activate the trigger. Save the project and run the deploy command in the terminal. 

firebase deploy --only functions

Make sure your Firebase project is upgraded to the Blaze plan before executing the command or you will not be able to deploy the function.

The Firebase Blaze plan is free until you reach a certain quota. For this tutorial, it will cost nothing.

Once the deployment is completed, go to the Firebase console. In the Functions tab, you should see the function in the system.

Image from Codeible.com

Subscribing to a Topic

Now that we have our trigger set up, we need to let the user subscribe to the topic we are broadcasting to. 


Go to the MainActivity of your Android application. Import FirebaseMessaging and create an instance.

import com.google.firebase.messaging.FirebaseMessaging;

public class MainActivity extends AppCompatActivity {

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

        FirebaseMessaging firebaseMessaging = FirebaseMessaging.getInstance();

    }
}

To subscribe to a topic, take the FirebaseMessaging object, call the subscribeToTopic() method, and pass in the topic you want to subscribe to. 


Since we are broadcasting to the new_user_forum topic, we’ll put new_user_forum.

firebaseMessaging.subscribeToTopic("new_user_forums");

If we run the application and add a document to the Notifications collection, a notification will appear.

To reiterate what is happening in the background, when we launch our Android application, the user will subscribe to the new_user_forum topic. 


Then whenever a document is added to the Notifications collection, Cloud Functions will automatically fire off the trigger function and run the code to broadcast a message to the new_user_forum topic. 

When the message is sent, the Notification Service will create a notification and display it on the device.


Sign In