Firebase Cloud Messaging Push Notification for Android……

Booyaaaah , In this I will show you how android push notification works by using back end server as a sender and a Android as a receiver.
Some background of Notification
A notification is a message that Android displays outside your app’s UI . It is usually used for providing reminders to user , For communications purpose you can easily send message with out going inside application , or you can provide direct action towards maps or any android activity according to your needs.
This shows simple example of notification

Prerequisite for this tutorial
Some basic knowledge of android platform
Some basic knowledge of core java
Some basic knowledge of REST APIs call
Android studio
Firebase Account
So let’s start learning , for this you need to just follow below steps
Step :1 Create Firebase account with this link and register your application to Firebase if you are facing issues to register find below link.
It will help you for this — https://darshanthakkar1569.medium.com/how-to-configure-firebase-project-in-your-android-application-70c580ac358d
Let’s get Server Key information which will be required for backend Server.
- First go to the project settings in top-left icon placed at your firebase console.
2. Then click on Project settings.
3. Find service accounts and click.
4. Find Generate new key pair which will generate file which be configuration file of your project, download.

Then we will need 1 back end server and 1 Message receiver service that can be anything android application , IOS application web application or any Game written in Unity.
Step 2 : You can make your server in any of the back end preferable language I will show you it in Node.js don’t worry you won’t need any prior knowledge just follow below steps.
Install Node.js from here, https://nodejs.org/en/ and check node -v in you command line interface for windows in cmd , for Linux go to terminal , then it should display version of Node.js
Install npm from here : https://docs.npmjs.com/downloading-and-installing-node-js-and-npm
- Make a folder in directory reach to that location by ‘cd <path>’ command.
Hit command npm init -y it will ask some information about your project and fill and hit enter….. after few steps booyyyahhh you will get your node project ready and you will be able to see package.json file created with provided information.
- After 2nd step we will need some dependencies for server like firebase-admin which will for push notification, express for node server , body parser for JSON body parsing .
npm i express firebase-admin body-parser
Now let’s start coding some boring stuffs are done let’s do some coding 😜😝.
Now Copy paste security key configuration JSON file generated in earlier step.
Create payload-model.js which is payload for making post request to Firebase. This file will make message as your need for you.
So For sending notification you will need to send payload as a json like as below :
For multiple devices —
{
data: {
title : “Title of your Notification”,
body: “Actual message of Notification”
},
tokens:[]
}
For single device —
{
data: {
title : “Title of your Notification”,
body: “Actual message of Notification”
},
token:”Device Token (I will show you, how to generate below)”
}
Create notification-config.js file in your project folder and write code as below :
Whoooaaaaa😛 our configuration file is ready , let’s understand what is actual meaning of our code ,
First we have imported firebase-admin dependency and security configuration file with appropriate path in our app and payload model which will be posted to Firebase as a json.
Then we have just initialized Firebase application with initializeApp() method which take json as a argument of credential key with certificate value.
Then we have written out sendNotification() method with title , body and tokens which will prepare and send your message to Firebase server.
Here,
title :- Title of your push notification ,
body :- Your actual message,
tokens :- Unique IDs for devices
Note :- If you want to send notification to multiple device then use sendMulticast() otherwise sendDevice() method.
sendMulticast() :- is the function used for sending notification which takes payload object which we have prepare above.
sendDevice() : — is the function used for sending notification which takes options json , message payload like as below
- options JSON : {
priority: “high”, timeToLive: 60 * 60 * 24 ,
}
- payload object I have defined in earlier steps you can see over there.
- call method like admin.messaging().sendDevice(payload,options).then(…
Create index.js in same folder , it will be work as a server for us and look like as a below.
Let’s understand the code …..
First I have imported certain files and dependencies like notification-config , express , body-parser respectively.
Then I have initialize an express application so I can run a server successfully on given PORT (2767).
Then I have made one end point ‘/sendNotification’ which handles rest call and send notification to given devices (tokens defines devices).
Boooyaahh your server is ready run node index.js in preferred command prompt to run the script.
Then you can call service from an REST client you have like POSTMAN ,etc.
And you can see the out put .
Step :3 Android Service that will receive notification sent from Node.js server.
Open Firebase registered Android Project in Android studio , if you are facing issue in this just follow this blog https://darshanthakkar1569.medium.com/how-to-configure-firebase-project-in-your-android-application-70c580ac358d.
There you need to do 1 steps to receive notification on your android phone.
1st step : Make a HandleFirebaseService.java which will receive notification from Firebase show it to device.
First let’s see what is FirebaseService ?
Firebase Service is service class which act as a receiver. It has certain callbacks method like onMessageReceived() , onDeletedMessages(), onMessageSent(), onSendError(), already received message(), etc… don’t worry as you will practice it more you will get deep knowledge about all this methods or you can find official document of Firebase for other methods.
onMessageReceived() :- When a message is psyched from back end server at the android side this method is called. So we will use this callback for showing notifications on the android side. So the logic behind this is we will override this method in our service and write some code for showing push notifications.
public class HandleFirebaseService extends FirebaseMessagingService{
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
showNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));
}
public void showNotification(String title, String message) {// copy and paste icon named image in your drawable folder
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "oxygen-detector")
.setContentTitle(title)
.setSmallIcon(R.drawable.icon)
.setAutoCancel(true)
.setContentText(message);
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
manager.notify(999, builder.build());
}
}
And showNotification() method prepare the Notification with Notification Builder and notify the notification manager to show the notification.
2nd step: Register services in the manifest so Your application could receive the notification in the background as well. This can be done with the below code,
Write this in AndroidManifest.xml
<application>....
....<service
android:name=".HandleFirebaseService"
android:directBootAware="true"
tools:targetApi="n"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>....
....</application>
That’s all Booyyyyaaaahhh, Android client is ready to receive notifications.
Now let’s learn to get device tokens for android which you will be required while sending requests from your POSTMAN.
Add the below method in one of your activity’s onCreateMethod() and run your application and search in logs ‘Firebase Token — > ’ it will print device token get that Hoorrrrayyyyy…..
Conclusion
So that’s all for now let’s conclude what we have learned,
We have made a Back end Server with Node.js which manages to push notifications to Firebase..
We have made an Android Client Application that receives notifications from Firebase..
Big Thanks to you techies !!!!!!
Having Problems 😴🤔🤔🤔 Reach out to me :
Instagram : https://www.instagram.com/darsh1507_official/
Linked In : linkedin.com/in/darshan-thakkar-539441106