Google Firebase Cloud Messaging or Push Notification Integration in Android Apps, Send RealTime Messages in Android App

Android Code Lab
AndroidCodeLab
Published in
10 min readJun 19, 2020
Firebase Push notification : Android

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost. FCM is completely free and there are no limitations. You can send notification messages to drive user re-engagement and retention. For use cases such as instant messaging, a message can transfer a payload of up to 4KB to a client app.

1. Firebase Message types

Using Firebase Cloud Messaging you can send three types of messages i.e Notification Message, Data Message and Hybrid Message.

Notification Message : are handled by firebase SDK itself or by developer. These type of message have such data tags limitations like body(Message), title(Title), click_action(Action on click KEY), icon(name of the icon) and the notification will be shown automatically and only when the app is in Background. In case of Foreground this message appears on your MyFirebaseMessagingService Class (Which explained below) so that you can personally handled them.

Data Message : are handled by Developer itself only. These type of messages provide you your own mechanism to create own payload json structure with your own custom tags or keywords. This type of messages have only one limitation which is 4 KB payload size but actually that is very enough for any app. For more than 4KB message size you can use them in other way like to call an api code to start calling. In any case either Background or Foreground these message appears on your MyFirebaseMessagingService Class (Which explained below) so that you can personally handled them.

Hybrid messages : with both notification and data payload. When these kind of messages are sent, it will be handled in two scenarios depending upon app state

When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.

When in the foreground, your app receives a bundle with both payloads available.

Here is a JSON-formatted message can containing both notification and data:

{
"to" : "fcm tokens",
"notification" : {//by default tags and your data
"body" : "message",
"title" : "title",
"icon" : "icon-tag"
},
"data" : {//custom json structure
"KEY" : "data",
"KEY" : "data"
}
}

For API implementation you can go through : Send FCM Push Notification and Data message to Android,IOS & Web in C#

Send FCM Push Notification and Data message to Android,IOS & Web in C#

2. Firebase Integration

Now lets do some work to make your app to enable FCM Push notification feature :

Project setup :

  1. Create a new project in Android Studio from File ⇒ New Project. While filling the project details keep in mind that your package name is same gonna used in firebase console. Project name is optional you can use different or same as per your will.
  2. In you android studio, at top-end corner there is an option to sign in your android studio. Go and sign in there to enable Easy FCM Setup Feature. This will take you to your default browser and you can start signing your email with android studio.
  1. After signing in, you get a window to allow Android studio to use and access some permissions for managing purpose you can allow them without any thought because without it you cannot proceed
    This image show you popup look like
  1. After allowing you saw two options of enabling Firebase or Cloud Platform. You can go with Firebase enabling after clicking firebase this will lead you to firebase website and you can take survey of there informative website

Now lets go back to the Android studio and start integrating Firebase into your project.

Step 1 : Start by using Android studio Firebase plugin :

As shown in image you can start default Firebase plugin by click there : Tools ⇒ Firebase

this will open your Studio Firebase assistant which have all the firebase feature with there documentation and steps to integrate them.

Leave other feature for next tutorials, lets focus on Cloud Messaging Feature placed in second position;

Step 2 : Click on Setup Firebase Cloud Messaging :

this will explore window like as shown in next image.

This window have complete steps and documentation to integrate this module of Firebase. For now you can read them if you want to otherwise

you can leave them on me, i can explain them briefly.

From here your FCM setup process initiate like you see here. there are two buttons Connect to Firebase and Add FCM to you App. These two steps lead you automatic setup of your project with Firebase console. Now you don’t need too much with your hands this tool do your all basic setup.

Step 3 : Lets start : First you need to Click Connect to Firebase button.

As shown below image this popup will appear on clicking button :

Now you can see firebase console with your account deatils and options required to complete this process.

  1. Create new project : this is what your requirement is to create and setup your project into firebase console without any effort this will do your all work in couple of seconds. Name your project you can set same or other name as per your will.
  2. Choose an existing Firebase and Google Project : here you saw your all list past project if you created before. If you choose one of them in your new project they will act like parent of your new project and your project add on them as a sub child or directory. Actually i don’t recommend you to go with this for your New type of project because this will be used for same sub child product of parent product and also there google-services.json file which is your project signing part is different and merged with parent.
  3. Country/Region : Simple option just add your country by selecting from drop-down.

By clicking Connect to Firbase of this Popup, your setup progress start and build your project and this will create your project into firebase console with Your Unique hash key of your system and also put google-services.json file to automatically on there place. your can see him after completing setup and build into

Either by Studio : Project Mode of your project ⇒ app ⇒ src ⇒ google-services.json. you can explore it and can check it this will have your project related information like project_id, project_name, some keys, cliend_id, package info and other things you can check your own.

or by Folders Project Folder ⇒ app ⇒ google-services.json.

Lets leave this now,

Step 4 : Click Button Add FCM to your app :

On clicking you saw dialog window like show in image below :

This button is act like magic button who add required dependency to your Project Gradle File.

Sample code :

app/build.gradle

dependency{//Firebase messaging latest dependency implementation 'com.google.firebase:firebase-messaging:like 17.0.0'//{add latest version}}//Add google plugin for using google servicesapply plugin: 'com.google.gms.google-services'

project/build.gradle

//Firebase buildscript dependency buildscript {    repositories {        jcenter()        google()    }    dependencies {        classpath 'com.android.tools.build:gradle:3.1.3'        classpath 'com.google.gms:google-services:3.2.1'    }}

Like Setup shown below in image

This is enough with auto work, now you need to dirty your hand with little simple java classes declaration and AndroidManifest setup :

Step 5 : Declare Messaging Service class which provide you access token and payload :

As shown in assistant tools description too :

Note : this will only refresh in case someone clear app data or reinstall the app, so keep upto date user with this if you saving this on your Server.

Firebase Messaging Service provide you, your payload data when it arrive.

public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "Jamun";
@Override
public void onNewToken(String token){
super.onNewToken(token)
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
// sendRegistrationToServer(refreshedToken);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
}

Complete view example is shown below :

Last but not least and Most important part :

Set app context to initialize app to Firebase : I recommend you all to use Application class for this scenario which is actually a best approach for App settings.

Example demonstrate you complete implementation :

public class MyApplication extends Application {private static MyApplication mInstance;
@Override
protected void attachBaseContext(Context context) {
super.attachBaseContext(context);
}
@Override
public void onCreate() {
super.onCreate();
FirebaseApp.initializeApp(this);
}
}

Step 6 : AndroidManifest Declaration which is necessary for every service declaration schemas :

Firebase Messaging Service declaration :

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

Firebase InstanceId Service declaration :

<service
android:name=".services.MyFirebaseInstanceIdService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>

Now some important setting no-one teach you
how to set your notification icon view and there color properties for default showing notifications :

Note : Keep your drawable as an icon must not an image here because from OS lolipop it shows white dot only if you used image insted of icon
to create and Icon you can used these Cool tools : Android Assest Studio

<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/icon_notification" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorPrimary" />
Note : For OS version Oreo and above you need to set channel id with Firebase Notification without it they failed to
show in your app :
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="com.techcruzers.filemanager.one" />
Complete view example is shown below :

Step 7 : Now learn how to Use Firebase console to push your First Firebase Notification into your app :

First open Firebase Console using link : Firebase Console

this will lead you to your dashboard if you are signed in with the same email you registered with before.

Now as shown in image below your dashboard will be look like this :

On clicking your project you saw your App with PackageId and Firebase Navigation Console with so many options, you need to scroll down and you saw in Grow ⇒ Cloud Messaging :

On Clicking Cloud Messaging your Notification window will be appear in main view :

Now if you have not any Notification history you saw a Button like Create your First Notification, click there and you saw your Compose Message window which have different EditText Fields.

Message Text : this field you need to enter with your content or message you want to push. Its upto you how much long or short message you want to Push.

Delivery Date : this used to set your delivery time of your notification you want to set or not its upto you.

Target : It is another but important field in notification composing that let you know three way of selecting user :

1. User Segment : This one provide you One app selection property so that you can hit target with same app.

2. Topic : As you saw above in JSON Structure of Message there is a Tag “to” which will lead you to your user this will be differentiate there you can push notification into those user who are registered as some Topic differences:

To set topic in your app or to devices you need to set it when Firebase InstanceId Token provided to your app in class : InstanceId Service.

Example explain you setup procedure of a Topic :

FirebaseMessaging.getInstance().subscribeToTopic(FRIENDLY_ENGAGE_TOPIC);

JSON structure of Your Topic id :

{   
"to" : "topics/msg",
"notification" : { },
"data" : {}
}

3. Single Device : Get any device or User FCM token and enter this below then you can send personal notification
using this console.

The Compose message with dummy data look like this image :

In this way, we have learnt how we can Send FCM Notification and Data messages to android devices using Push Notification Service Of Firebase Console.

If you have any problem than you can refer this video

Thank you,

For any queries please feel free to comment…!

--

--

Android Code Lab
AndroidCodeLab

Android Code Lab is a world for Android Nerds which provide Android libraries, codelabs, tutorials, Custom code classes and many more to make you 0 to infinity.