What is Firebase Cloud Messaging?
It is a service provided by Google. Google says “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.
- Notification Message: Notification messages are handled by firebase SDK itself. Typically the notification message contains title, message, icon etc., These message can be sent from firebase console UI. By sending this kind of messages, you won’t get much control over the notification.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.
- 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
Creating a new Android Studio Project
- I have created a blank project using an Empty Activity, and I named it FirebasePushNotificationExample.
- So you have to do the same, you can change the project name to whatever you want.
Adding Firebase Cloud Messaging
- Click on tools and then select Firebase.
- It will open an Assistant Window on the Right. From here you need to Select Cloud Messaging (As shown in the image).
- Here you need to do two things.
Connect to Firebase
- Click on the first Button, Connect to Firebase.
- It will open a new Window.
- 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.
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.
- 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.
- 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.
- 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. Here we will learn about the FCM Token .
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.
MyFirebaseInstanceIdService.Java
package com.c1ctech.firebasepushnotificationexample;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {
//this method will be called
//when the token is generated
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//for now we are displaying the token in the log
//copy it as this method is called only when the new token is generated
//and usually new token is only generated when the app is reinstalled or the data is cleared
Log.d("Refreshed token: ", refreshedToken);
}
}
package com.c1ctech.firebasepushnotificationexample;
public class Constants {
public static final String CHANNEL_ID = "my_channel_01";
public static final String CHANNEL_NAME = "Simplified Coding Notification";
public static final String CHANNEL_DESCRIPTION = "www.simplifiedcoding.net";
}
- Now, create a class named MyNotificationManager and write the following code.
MyNotificationManager.Java
package com.c1ctech.firebasepushnotificationexample;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import static android.content.Context.NOTIFICATION_SERVICE;
public class MyNotificationManager {
private Context mCtx;
private static MyNotificationManager mInstance;
private MyNotificationManager(Context context) {
mCtx = context;
}
public static synchronized MyNotificationManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new MyNotificationManager(context);
}
return mInstance;
}
public void displayNotification(String title, String body) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(mCtx, Constants.CHANNEL_ID)
.setSmallIcon(R.drawable.app_icon)
.setContentTitle(title)
.setContentText(body);
/*
* Clicking on the notification will take us to this intent
* Right now we are using the MainActivity as this is the only activity we have in our application
* But for your project you can customize it as you want
* */
Intent resultIntent = new Intent(mCtx, MainActivity.class);
/*
* Now we will create a pending intent
* The method getActivity is taking 4 parameters
* All paramters are describing themselves
* 0 is the request code (the second parameter)
* We can detect this code in the activity that will open by this we can get
* Which notification opened the activity
* */
PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
/*
* Setting the pending intent to notification builder
* */
mBuilder.setContentIntent(pendingIntent);
NotificationManager mNotifyMgr =
(NotificationManager) mCtx.getSystemService(NOTIFICATION_SERVICE);
/*
* The first parameter is the notification id
* better don't give a literal here (right now we are giving a int literal)
* because using this id we can modify it later
* */
if (mNotifyMgr != null) {
mNotifyMgr.notify(1, mBuilder.build());
}
}
}
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.
package com.c1ctech.firebasepushnotificationexample;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//If the device is having android oreo we will create a notification channel
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(Constants.CHANNEL_ID, Constants.CHANNEL_NAME, importance);
mChannel.setDescription(Constants.CHANNEL_DESCRIPTION);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
}
//Displaying a notification locally
MyNotificationManager.getInstance(getApplicationContext()).displayNotification("Hi","Where are you?");
}
}
- Now try running your application.
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 -> Cloud Messaging.
- And after pressing the Send Message button, you should see your message on the application.
Hello .. nice tutorial ..but cyan u make tutorial when fcm push notification received .. it automatically save in our device and we can view again later ?
Hi Aiman, Thanks for the comment.
You can save the FCM data in Sqlite when application get the data in “onMessageReceived” method. I will post one tutorial for it soon.