Android App Development

How to Add Firebase Cloud Messaging (FCM) in Android Apps

What is Firebase Cloud Messaging (FCM)?

Firebase by Google is a free platform which gives us the tools to develop high quality apps, grow and earn money.
Here we are going to introduce about Firebase Cloud Messaging(FCM) which is an alternative of Google Cloud Messaging. It is easier in compared to GCM.
FCM is an API which delivers the message in the form of push notifications and it doesn’t depend on the platform for development purpose.
By using FCM we can easily inform the user about notifications and new data sync.
We can send instant messages up to 4 kb in size using FCM.
Here, we will create an application and will show how we can send push notifications to a single Android device by using FCM.

How to Add FCM in our App:

Before Creating application first, we have to add FCM with our app by getting a configuration file.
There are a few steps to it. Let’s see how we can very easily develop an application for push notifications.

  • Create an Application FCMExampleAndroid in Android Studio.
  • After successfully creating this application go to https://console.firebase.google.com/.
  • Open this official site and Sign In successfully.


It will look like this

  • after Sign In we have to Create New Project.


Here, we will give the same name of our project and select a country and then click on Create project.

  • Then the next screen appears, choose the second option i.e. Add Firebase to your Android app.

  • After this, we have to enter app details like package name of our project. Simply copy your package name from manifest file and paste it here.

  • Click on Add App. After this, it will download the google-services.json file. This is the configuration file of our app.
  • Copy this downloaded file into our app module root directory.


We can add this file like this in our application.

  • After this Go to the console and press continue then add the dependencies in your project and app-module build.gradle file.

<project>/build.gradle:
dependencies {
// Add this line
classpath 'com.google.gms:google-services:3.0.0'
}
<project>/<app-module>/build.gradle:
dependencies {
compile 'com.google.android.gms:play-services-basement:9.2.1'
compile 'com.google.firebase:firebase-messaging:9.2.1'
}

// Add to the bottom of the file

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

So, these are the dependencies we have to add for creating FCM in Android.

  • After this click on Finish button. It will add our app with FCM.
    Now, it’s time to add the functionalities in our application programmatically.Android Programming

Example with code:

After Adding the dependencies in our build.gradle file sync the project, then we have to create two subclasses of Service MyFirebaseInstanceIDService which extends FirebaseInstanceIDService and MyFirebaseMessagingService which extends FirebaseMessagingService.

FirebaseInstanceIDService:

This is a service class which is used to handle the registration token lifecycle. By using this we get the registration token from onTokenRefresh () method and later we will use this token for sending a message to a device or device groups.

FirebaseMessagingService:

This is a service class which is used to handle the message after receiving the notification on apps in the background. By overriding onMessageReceived() method we will generate the push notifications very easily.

MyFirebaseInstanceIDService.java:

Create this subclass of service and extend with FirebaseInstanceIDService in your application and add the code for getting registration token as we discussed above.

Add the code here:

private static final String TAG = "MyFirebaseIIDService";
@Override
public void onTokenRefresh() {
//Getting registration token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//Displaying token on logcat
Log.d(TAG, "Refreshed token: " + refreshedToken);
}

Here, we will generate the token by onTokenRefresh() method and get this with the help of logcat after successfully running this application.

MyFirebaseMessagingService.java:

Create this subclass of service and extend with FirebaseMessagingService and override its method onMessageReceived() then,

Add the code here:

private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
sendNotification(remoteMessage.getNotification().getBody());
}

Here, we will create a method sendNofication(…) it is a calling method to generate the notifications.

Add the code in this method:

private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Firebase Push Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}

Now, Add these services and internet permission in AndroidManifest.xml file.

AndroidManifest.xml:
Add the code here:

<!-- Adding Internet Permission -->
<uses-permission android:name="android.permission.INTERNET"/>
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>

Here, we add the permissions and services in manifest file like this.
Now, Run the application and get the token from logcat.

Here, we can see in logcat the refreshed token. Just copy this and go to firebase console and selects the application which you created.
Then select the Notifications from left bottom.

After selecting it will looks like this and then we can easily send push notifications to a particular device or device groups. Click on Send your first message.
Android Programming

The screen which appears here, we will type our message, message label, delivery date accordingly and choose the target.
Here we use the single device after this. We add the token here and send the message.

Press the Send Message button and check your device. We can see very well that it has received the notifications.

Output:

Push Notification using Firebase Cloud Messaging

Output On Firebase Console

Download Code: GitHub

Conclusion:

So, this is all about FCM in Android, it is just a simple example of how to use Firebase Cloud Messaging (FCM) on applications. Here, we get the configuration file i.e. json file by successfully creating a project on firebase console and use it in our application. By using token we can easily send push notifications to a single device as we see earlier. It is an important feature of Android development.

Android Programming

Tags

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Related Articles

Close
Close