Firebase Cloud Messaging (FCM) with Firebase Realtime Database and Cloud Functions

Preveen Raj
4 min readApr 15, 2019

A friend asked me whether I can help him find a way to send a push notification to his android phone when a data updation occurs in the Firebase Database.

I have heard from my friends that there is this thing called Firebase cloud messaging which help you do things like Thanos did it in a snap. With that knowledge, I started to mine information on how to implement this baby.

Stories apart, lets come to technical talk now.

Initially, we have to connect our Android app with Firebase Cloud Messaging Service, for that we must create a Firebase Project.

It can be done inside Android Studio by choosing, Tools > Firebase > Cloud Messaging and even a primary school student can do the rest.

Now create a java class MyFirebaseMessagingService.Java

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {


Log.d("MSG",remoteMessage.getNotification().getBody());
shownotification(remoteMessage.getNotification());



}






@Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.d("NEW_TOKEN",s);
}


public void shownotification(RemoteMessage.Notification message){


NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "com.****.*****.***"; //your app package name

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification",
NotificationManager.IMPORTANCE_DEFAULT);

notificationChannel.setDescription("Techrush Channel");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationManager.createNotificationChannel(notificationChannel);
}

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_notifcation)
.setContentTitle(message.getTitle())
.setContentText(message.getBody())
.setContentInfo("Info");

notificationManager.notify(new Random().nextInt(),notificationBuilder.build());

}

}

There are two functions, namely OnMessageReceived and onNewToken. The former function takes the remotemessage object as the parameter (which is the message send from the cloud). When a message is sent from the server, the function captures that message and here, we pass that message to another function called shownotification, which does the job to create a push notification, when the app is running, paused or even killed.

The later function, onNewToken takes a String s as a parameter, which is indeed is a token, used to identify the device for messaging service. So, when the app is launched, a token will be given for the app. Here, that token will be shown in the log (if you read the code, u may understand).

If it comes to use, you can get the token in your MainActivity.Java too by the following code:

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(MainActivity.this,new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult instanceIdResult) {
String newToken = instanceIdResult.getToken();
Toast.makeText(MainActivity.this, newToken, Toast.LENGTH_SHORT).show();
}
});

Now, update your Android Manifest file with the below code for the service to work:

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

Tedaaa…. now your app should be working! Wondering how to test? Goto your Firebase console, open up the cloud messaging tab, send a test message by providing the token of your app.

It was a surprise for me, when I received the notification, it should be for you too.

Now that we are able to send notifications from firebase, lets try to create a cloud function which listens to a variable in the firebase realtime database. Our aim is to get a notification via cloud messaging when the database value is updated.

Hence, we have to setup a Firebase CLI in our local system, so as to code in cloud functions and deploy it to the server.

You’ll need a Node.js environment to write functions, and you’ll need the Firebase CLI (which also requires Node.js and npm) to deploy functions to the Cloud Functions runtime.

In your cmd, start with the following commands…

npm install -g firebase-tools

To initialize your project:

  1. Run firebase login to log in via the browser and authenticate the firebase tool.
  2. Go to your Firebase project directory.
  3. Run firebase init functions. The tool gives you an option to install dependencies with npm. It is safe to decline if you want to manage dependencies in another way.
  4. The tool gives you two options for language support:

Javascript / TypeScript

For this tutorial, select JavaScript.

Now that you have created your project folder, navigate to the functions folder inside your project folder and find the index.js file. We shall edit this file to include cloud functions to be deployed into the server.

open the index.js file in an editor. Clear the text and paste the below code:

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();
exports.checkflag = functions.database.ref('/flagparent') //give your database path instead here.onUpdate((snapshot, context) => {const temptoken = 'yourapptoken'; //replace it with your app token// const flag = snapshot.before.val(); TO GET THE OLD VALUE BEFORE UPDATEconst flag = snapshot.after.val();let statusMessage = `Message from the clouds as ${flag}`
var message = {notification: {title: 'cfunction',body: statusMessage},token: temptoken};admin.messaging().send(message).then((response) => {console.log("Message sent successfully:", response);return response;}).catch((error) => {console.log("Error sending message: ", error);});});

now, save index.js file, and come back to the command line.

Type in the below code to deploy your function to the server.

$ firebase deploy --only functions

It might take a while for your functions to take effect Definitely not more than a minute).

Now, go to your database, and update it. You can see the notification firing like a shooting star!

--

--