Firebase Cloud Messaging

Sithara Rao
AndroidCodes
Published in
6 min readSep 20, 2020

--

This post would give a brief idea on Firebase and the implementation of FCM in the application.

Firebase is a platform developed by Google for creating mobile and web applications. It was originally an independent company founded in 2011. In 2014, Google acquired the platform and it is now their flagship offering for app development

Firebase is a Backend-as-a-Service that provides powerful features for building apps. It has core services such as Authentication, Cloud messaging, Crashlytics, Real time DB, performance monitoring etc,. Refer the link to know more about the firebase services.

Let us now understand FCM, Setting up the Firebase and a sample app for better understanding. Here we go!

What is FCM? ☁️

FCM refers to Firebase Cloud messaging. This is one of the core features provided by Firebase. If you need to send a notification to your app, you don’t have to build your own server. Yes! You read it right. Firebase does it for you without any cost!

Firebase Cloud Messaging is a cross-platform messaging solution that lets you reliably send messages at no cost.

Setting up Firebase:

Create a project in your Android Studio and start linking it with the firebase. Here’s how to do:

  1. Login to your gmail and then go to Firebase console: https://console.firebase.google.com/
Firebase console

2. Click on “Create a Project” and give it a name and click on continue

3. In the next step if you need to enable Google analytics, enable it and click on continue

4. Accept the terms and conditions and create the project

Once your project is successfully created, you will be taken to the below screen where we are allowed to add Firebase to our app based on Android, iOS or Web app

As, I will be linking the Firebase to Android app in the example, I will be choosing Android

Setting up Firebase to your application:

  1. On creating an application in your Android studio, copy the package name and fill in the details accordingly

The next step is to get the SHA-1 key. To do this, follow the below steps:

a) Open Android Studio and click on “Gradle” option on right hand side

b) Select the project and then go to Tasks -> android -> double click on signingReport. This generates debug signing certificate with SHA-1, SHA-256 and MD5 keys.

c) Go to Firebase console and paste the SHA-1. Click on “Register App” to continue.

2. The next step is to download the google services configuration file.

3. On successful download of “google-services.json” file, go to Android Studio and select Project view. Paste the downloaded file under app module with Project as root view. The file will have project related information that can be viewed

Project view -> app -> Paste the config file

4. Set up the project-level and app-level gradle dependencies

a) Project level dependency:

classpath ‘com.google.gms:google-services:4.3.3’. Choose the appropriate version based on the updates.

Project- level Gradle dependency

b) App level dependency:

apply plugin: ‘com.google.gms.google-services’

implementation ‘com.google.firebase:firebase-analytics:17.5.0’

implementation ‘com.google.firebase:firebase-messaging:20.2.4’

Add FCM and Firebase Analytics dependency (if chosen while project creation in Firebase console)

Sync the gradle changes with the app

5. Run the app in-order to verify if the app has communicated with Firebase cloud servers. If the app does not get verified, try clearing the data and open the app again. Else uninstall and re-install

App changes for receiving messages:

Step 1: Create your own service class and extend it with “FirebaseMessagingService

Step 2: Override onMessageReceived() and onNewToken() methods

public class FCMDemoService extends FirebaseMessagingService {

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

if (remoteMessage.getNotification() != null) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "New Message Received! " + remoteMessage.getNotification().getTitle(), Toast.LENGTH_LONG).show();
}
});
}
}

@Override
public void onNewToken(@NonNull String s) {
super.onNewToken(s);
}
}

Step 3: onMessageReceived() is called when there is any new push notification received from FCM server. We get RemoteMessage as object. Based on the data, we can implement the action to be performed.

onNewToken() is called when the service gets registered in the manifest and called when we first run the app. Firebase sends a new token for the app everytime.

Step 4: To get a token, we need to add the following code in our activity:

private void getFCMToken() {
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.e(TAG, "getInstanceId failed" + task.getException());
return;
}

String token = task.getResult() != null ? task.getResult().getToken() : "Token is null";
Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
}
});
}

Why Token is needed? Here’s the answer:

Every app has to be identified with a unique access key. This key is needed for sending notifications to a particular device and to know if the app is really has the Firebase enabled for receiving messages.

Step 5: Register the service in manifest:

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

</service>

Testing:

Step 1: Go to Firebase console

Step 2: Go to “Grow” option on the left side and click on Cloud Messaging

Step 3: Click on “Send your first message”

Step 4: Enter notification title and description:

Test notification

Step 5: Choose your application package

Step 6: You can schedule the notification or sent it right away

Step 7: Publish the notification :)

And its done!!

As per the code, we are showing a toast that displays the notification title. So when the notification is received, we would have something like this in our app

We can even show the notification in the app if we need to engage the user with recommendations, new stock arrival, breaking news etc,. Make the whole use of FCM to bring-in features in your application

Stay tuned for updates. Happy coding! 🙋‍

--

--