Firebase Cloud Messaging Tutorial for Android

Push notifications are apparently an essential thing in Android Application. It helps us gaining user retention, increasing active user, etc. To send a push notification to all our app users, we can use Firebase Cloud …

firebase cloud messaging tutorial

Push notifications are apparently an essential thing in Android Application. It helps us gaining user retention, increasing active user, etc. To send a push notification to all our app users, we can use Firebase Cloud Messaging. We can send some promotional as well as regular information using Firebase Cloud Messaging (or FCM) very quickly.

So this post is about Firebase Cloud Messaging, and today we will learn how we can use Firebase Cloud Messaging in our android application.

What is Firebase Cloud Messaging?

It is a service provided by Google. So what Google says is “Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost.”

So it is free and at the same time easy to use. Previously we were using Google Cloud Messaging, but nowadays GCM is obsolete. So you should use firebase only

Message Types

Before moving ahead in the post let’s first understand the types of message that can be sent using FCM.

  1. Notification Message: This type of message is automatically displayed to end user. In this kind of message, we have a predefined set of key-value pairs. We also have a data payload by using it we can set the custom key-value pairs as well.
  2. Data message: Default does not display this type of message to the end user. To show it we need to add some coding. This message contains only custom key-value pairs.

Adding Firebase Cloud Messaging to Android Project

As always the first step is creating a new Android Studio Project.

Creating a new Android Studio Project

  • I have created a blank project using an Empty Activity, and I named it FirebasePushExample.
  • So you have to do the same, you can change the project name to whatever you want.

Login into Android Studio using your Google Account

If you have logged in already into your Android Studio with your Google Account, then you can skip this step. 

  • You will see a user image at the top right corner of your Android Studio IDE. Click on this icon.

firebase cloud messaging tutorial

  • Now click on the Sign In button. And then authenticate with your Google Account.

Yes, a Google Account is necessary, and if you are an android developer then it is apparent that you are having a google account right? 

Adding Firebase Cloud Messaging

After logging in to Android Studio with your Google Account, you can quickly add Firebase Cloud Messaging to your project.

  • Click on tools and then select Firebase.

firebase cloud messaging tutorial

  • It will open an Assistant Window on the Right. From here you need to Select Cloud Messaging (As shown in the image).

adding firebase

  • Here you need to do two things.

Connect to Firebase

  • Click on the first Button, Connect to Firebase.

connect to firebase

  • It will open a new Window.

Android Connect to Firebase

  • From here you can create a new Firebase Project, or you can also select your existing project on firebase if any. Here we are building a new Firebase Project. Just put the name that you want for your project and click on Connect to Firebase.
  • Now wait for a while, and you will see Green Connected Message.

fcm connected

Add FCM to your app

  • Now click on the second button. Add FCM to your App. It will again open a new window, and here you need to accept the changes.

add fcm to your app

  • Then it will automatically do everything required for adding FCM to your application.

Ways of Receiving Push Notification

Now first, we need to understand how we receive or send notifications using FCM. So there are two ways.

  1. Using FCM Token: We use this method when we want to send a notification to a specific device. Or some dynamic group of devices. Upon initial startup, the firebase SDK generates a registration token for the application. We use this token to identify the device.
  2. Using Topic: We can create topics and let our users subscribe to those topics. Then we can send the message to the topic. And the message will be sent to all the users of that particular topic. In this method, we don’t need to store any token.

We can select from the above two methods to implement in our application. We can use both ways as well. First, we will learn about the FCM Token then we will see the Topic method as well. So let’s do it. 

Firebase Cloud Messaging using FCM Access Token

In this method first, we will generate the access token. Now to get the access token, we create a class that extends FirebaseInstanceIdService. It is a service that we also need to define inside our Manifest file. Now let’s see how we can do this in our project.

Generating Access Token

  • Create a class named MyFirebaseInstanceIdService in your project, and write the following code.

  • As this class is a service, we need to define it in AndroidManifest.xml as well.
  • So open your AndroidManifest.xml file and just before the closing </application> tag add the following code.

  • Now run the application, and you will see the token in your logcat.

refreshedtoken firebase

  • Now copy this token and save it anywhere on your system. We will use this token to receive notification.

Common Issues

Keep these things in mind if you are not getting the token. 

  1. The token is not everytime generated. We get the token only when firebase refreshes the token. So it might happen that once you run the application and by mistake cleared the log. Then if you again run your application, you will not find the token. So, in this case, you have to uninstall the app, and then you need to again run it. 
  2. Google Play Service version should be higher than the Firebase version that you are using in your project. It is always better to update the Google Play Services to the latest version. 
  3. You are seeing the log of a different emulator or device. Confirm that emulator selected in the top of the logcat is the same where you are running the application. 

Receiving Messages

To receive the message we need to create a class that will extend FirebaseMessagingService. Here we will override a method onMessageReceived() that is called when we receive a message. Again this is also a service, so we need to define it in our AndoirdManifest.xml

  • Create a class named MyFirebaseMessagingService and write the following code.

  • Now again define it using the below XML code in your AndroidManifest.xml just before the closing tag </application>.

  • But to see the notification we need to build it. So now let’s make the notification.

Building Push Notification

Now let’s build the Push Notification. For this, I will use a Singleton class.

Note: From Android Oreo, you need to create a notification channel or else notification will not be displayed. 

  • So first we will define some constants for our Notification Channel in a separate class. Create a class named Constants. And write the following code.

  • Now, create a class named MyNotificationManager and write the following code.

Testing a Local Notification

Before moving ahead, we will confirm that the notification is working correctly. For this, we will create a local notification from the app itself.

  • Come on MainActivity.java and write the following code.

  • Now try running your application.

Sample Notification

  • If you see this then awesome, it is working.

Testing Notification from Firebase Console

  • Now let’s send a real notification from Firebase Console.
  • Open firebase console, then open your project that you are using. Then from the left menu click on grow -> notifications. 

Firebase Cloud Messaging from Console

  • And after pressing the Send Message button, you should see your message on the application.

Firebase Cloud Messaging Sample Notification

  • As you can see it is working fine, as we see the notification.

Firebase Cloud Messaging using Topic Subscription

Now let’s see how we can send to notifications to the devices that are subscribed to a particular group. Obviously, for this, we need to create a group first. So here is the method.

  • Call FirebaseMessaging.getInstance().subscribeToTopic(“put_your_topic_here”);
  • The above method will subscribe the user to the topic, if the topic is not an existing topic firebase will create the topic specified.
  • Now here in your application, we will give some topics to the user to subscribe. For this let’s create the interface.

Creating Interface

  • Go to your strings.xml file and define the following array. These are the topics that a user can subscribe.

  • Now copy the following for activity_main.xml.

  • The above code will generate the following UI.

fcm topics

  • From here user will select the topic and then click on the button to subscribe.

Subscribing to a Topic

  • Now modify your MainActivity.java as below. The code is straightforward and self-explaining.

  • Now again, try running your application.

subscribe to topic

  • Yes, it is working fine. Now let’s try sending a notification to this topic.

Sending Notification to Topic from Firebase Console

  • Again go to the firebase console and go to the notification.
  • Now this time we will select send to the topic instead of a single device.

notification to topic

  • After clicking on send, you should see the notification on your device.

topic notification

  • Bingo! It is working fine.

Unsubscribing from a Topic

Sometimes user also wants that “I don’t want to receive notification”.  In this case, you have to give an option to unsubscribe as well.

  • To unsubscribe from a topic, you need to call FirebaseMessaging.getInstance().unsubscribeFromTopic(“your_topic”);

Firebase Cloud Messaging Tutorial Source Code

If you still have some problem following the post (it was very long, you have to follow it carefully) then here I have my source code in my GitHub repository. You just need to unlock the link by using a social button given below.

[sociallocker id=1372] Firebase Cloud Messaging Tutorial Source Code [/sociallocker]

So that’s all for this Firebase Cloud Messaging Tutorial friends. In the next post, we will learn to build our admin panel to send and manage notifications. If you found this firebase cloud messaging (FCM) tutorial helpful then please SHARE it with your friends. Thank You 🙂

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.

Expand Your Knowledge: Next Tutorial Picks

0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x