What Is Firebase Push Notification In Android & How It Works?
CONTACT

Easily Understand How To Send Notification In Android Using Firebase!

Sitaram Sharma By Sitaram Sharma | July 26, 2021

One of the most asked queries by developers is how to send notification in Android using Firebase? Over the years, the challenges faced by backend developers have been addressed by Firebase. It is known for providing push notifications services across various OS platforms.

Firebase is a Backend as a Service (BaaS) platform that acts as a solution provider for developers. It solves many issues regarding databases, notifications, authentication, etc.

This blog will provide you a complete analysis of how firebase attempts to solve the backend issues of the mobile. Any mobile app development company will resolve your notification issue.

Wanna Find Out What Is Firebase Push Notification In Android? Simplified below!

Before we jump into the crux of the matter, let’s get to know what push notification is. A push notification is an alert you get on your mobile while you are away or using another app. This prompts you to come back to the app and check out what you’re missing. 

The main purpose is to get your time invested in using the app as much as possible. Let’s try and understand push notification in the Android example which will clear your doubts.

how flow of push notification mechanism works

#1 – Application Server

This is the very beginning that defines the initiation of the generation of push notifications. For example, someone tagged you on Facebook, then the application server will send the instruction to the notification server.

#2 – Notification Server

Notification server is the place where it’ll get the instructions for pushing the notification to the device. For android phones, the server is Google’s and for iPhones, the server is from Apple. 

Once the instruction for carrying out notification reaches the server, then it proceeds to send it to the device. For an optimized server response, you can implement some effective strategies for cloud migration. It will enhance the server response due to new services.

#3 – Device

The device can be iOS or Android, therefore the server notification matches the device. Once the device is matched by the notification server, Apple or Google, then it pushes it to the device.

The device receives the notifications in a push format. It means that if you’re using the device, then a notification will appear on your screen. Implementing Firebase push notification is one of the pre and post app launch snags to avoid

Look At What FCM Is In Simple Points – Details Explained!

Firebase Cloud Messaging (FCM) offers an expansive scope of informing choices and capacities. The data on this page is planned to assist you with understanding the various kinds of FCM messages and how you can manage them. 

With FCM, you can send two kinds of messages to customers: 

Warning messages, now and again considered as “show messages”. These are dealt with by the FCM SDK consequently. 

Notification messages, which are dealt with by the custom mobile apps for business

#1 – Warning Messages

Warning messages contain a predefined set of client noticeable keys. Information messages, paradoxically, contain just your client characterized custom key-esteem sets. Notice messages can contain a discretionary information payload. The most extreme payload for both message types is 4000 bytes, with the exception of when sending messages from the Firebase console, which implements a 1024 person limit.

image explaining the difference between the 2 messages

Use notice messages when you need FCM to deal with showing a warning for your customer application’s benefit. Use information messages when you need to handle the messages on your custom application. Make sure you have the top tech upgrades for businesses that can handle immediate responses and messages.

FCM can send a notification message including a discretionary information payload. In such cases, FCM handles showing the notification payload, and the customer application handles the information payload. 

#2 – Notification Messages

For testing or for showcasing and client re-commitment, you can send warning messages utilizing the Firebase console. The Firebase console gives investigation-based mobile app usability and testing to assist you with refining and further developing advertising messages. 

To automatically send notification messages utilizing the Admin SDK or the FCM conventions, set the warning key with the vital predefined set of key-esteem alternatives for the client apparent piece of the notification message. For instance, here is a JSON-arranged warning message in an IM application. The client can hope to see a message with the title “Portugal versus Denmark” and the content “extraordinary match!” on the gadget.

Addressing The Query – How To Get FCM Registration Token In Android?

Getting a token is one of the most important things if you wanna register for FCM. However, you must go through certain steps. Using the code,fcm token example, mentioned below you can resolve the issues.

#1 – RegistrationIntentService.java

public class RegistrationIntentService extends IntentService {

 private static final String TAG = “RegIntentService”; 

public RegistrationIntentService() { 

super(TAG); 

} @Override 

protected void onHandleIntent(Intent intent) { 

String token = FirebaseInstanceId.getInstance().getToken(); 

Log.i(TAG, “FCM Registration Token: ” + token); 

}

#2 – MyFirebaseInstanceIDService.java

myfirebaseinstanceidservice code helps in fcm push notification android

// [START refresh_token] 

@Override

 public void onTokenRefresh() { 

// Get updated InstanceID token. 

// String refreshedToken = FirebaseInstanceId.getInstance().getToken(); 

// Log.d(TAG, “Refreshed token: ” + refreshedToken); 

// 

// // TODO: Implement this method to send any registration to your app’s servers. 

// sendRegistrationToServer(refreshedToken); 

// 

Intent intent = new Intent(this, RegistrationIntentService.class); startService(intent); 

// [END refresh_token] 

/** 

* Persist token to third-party servers. 

* <p> 

* Modify this method to associate the user’s FCM InstanceID token with any server-side account 

* maintained by your application. 

* @param token The new token. 

*/ 

private void sendRegistrationToServer(String token){ 

// Add custom implementation, as needed. 

}

}

In addition, you’ll have to put this in the MainActivity.java.

Intent intent = new Intent(this, RegistrationIntentService.class); startService(intent);

This code will definitely help you in fcm push notification android to get the registration token for android! Once you get the token registered, then communication between the server and the device will be hassle-free.

Read our comprehensive backend development tutorial.

Using the example and the steps above, your query on how to get fcm token in the android studio will be addressed.

What’s The Working Of Firebase Push Notification From Spring Boot? Explained Easily!

The working of Push notifications using Spring Boot can be troublesome. To simplify this, you can check out the steps that have the code written in concise. Take a look at them below to clarify your doubts.

#1 – Setup Firebase Messaging Dependency

<dependency>

     <groupId>com.google.firebase</groupId>

     <artifactId>firebase-admin</artifactId>

     <version>7.0.0</version>

</dependency>

#2 – Get Service Account Private Key from FCM Console

screenshot providing clarity on firebase push notification from spring boot

#3 – Configure Spring Bean For Push Notification

@Bean

FirebaseMessaging firebaseMessaging() throws IOException {

    GoogleCredentials googleCredentials = GoogleCredentials

            .fromStream(new ClassPathResource(“firebase-service-account.json”).getInputStream());

    FirebaseOptions firebaseOptions = FirebaseOptions

            .builder()

            .setCredentials(googleCredentials)

            .build();

    FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, “my-app”);

    return FirebaseMessaging.getInstance(app);

}

#4 – Write A Push Notification Service

@Service

public class FirebaseMessagingService {

    private final FirebaseMessaging firebaseMessaging;

    public FirebaseMessagingService(FirebaseMessaging firebaseMessaging) {

       this.firebaseMessaging = firebaseMessaging;

    }

    public String sendNotification(Note note, String token) throws FirebaseMessagingException {

        Notification notification = Notification

                .builder()

                .setTitle(note.getSubject())

                .setBody(note.getContent())

                .build();

        Message message = Message

                .builder()

                .setToken(token)

                .setNotification(notification)

                .putAllData(note.getData())

                .build();

        return firebaseMessaging.send(message);

    }

}

#5 – Write A Test Controller

@Data

public class Note {

    private String subject;

    private String content;

    private Map<String, String> data;

    private String image;

}

/*******************************/

@RequestMapping(“/send-notification”)

@ResponseBody

public String sendNotification(@RequestBody Note note,

                               @RequestParam String token) throws FirebaseMessagingException {

    return firebaseService.sendNotification(note, token);

}

#6 – Verifying Push Notification From Spring Boot

$ curl -X POST “http://localhost:8080/send-notification?topic=gold” \

  -H “Content-Type: application/json” \

  -d ‘{

    “subject”: “some subject”,

    “content”: “Some long content”,

    “image”: “https://somedomain.com/example.jpg”,

    “data”: {

      “key1”: “Value 1”,

      “key2”: “Value 2”,

      “key3”: “Value 3”,

      “key4”: “Value 4”

    }

  }’

HTTP/1.1 200 

Content-Type: text/plain;charset=UTF-8

Content-Length: 53

Date: Thu, 10 Sep 2020 14:21:50 GMT

Keep-Alive: timeout=60

Connection: keep-alive

projects/spring-demo/messages/2282285117414704507

#7 – Summary & Sample Code

This is how push notification value increases with intensity using Spring Boot. In the above explanation, a real example has been demonstrated for better understanding.

Wanna Know How To Send Push Notification From Firebase Console? Check Out Below!

To get an understanding of how to send notification in android using firebase go through the points mentioned below.

1 – Sign in to the Firebase Console (https://console.firebase.google.com )

2 – In the route bar, click Notifications.

  • In the event that this is your first warning, you’ll see a “Send your first message” button. Snap it. 
  • In the event that you have effectively sent a few warnings, you’ll leap to your messages list. Snap New Message. 

3 – Enter the message in the Message text field. (Tip: in the event that you surpass the 1024 person limit, all that you have entered will evaporate and you’ll need to begin once again.)

4 – (Discretionary yet suggested.) Enter a message name. This isn’t seen by your audience members; it is simply used to distinguish the message in your Firebase message list.

5 – Set the conveyance date and time region. You can pick Send Now, or you can choose to Send Later and pick a date and time as long as one month later. However on the off chance that you need to send the message to all clients simultaneously, un-select this and pick a time region from the rundown.

6 – Set your objective choices. You need to pick which application (iOS or Android app development) to target, then, at that point add any extra objective alternatives. On the off chance that you need to target both applications, finish the focusing of the first then, at that point click Target another application and set it up for the second application. 

7 – Leave the Conversion occasion settings with no guarantees. (Sent and Opened measurements are given naturally, and the excess things don’t make a difference to your applications.)

8 – (Discretionary.) Expand the Advanced Options area.

9 – Either save the message as a draft that can be altered later, or snap the Schedule message.

How Can Notification Be Sent To Select Users Using FCM?

A query like, how to send a notification to specific users with FCM?  Can create curiosity. In that case, you’ve come to the right place. You can use the assistance provided by us below. This will ensure that you can send the notifications to only the people that you deem necessary.

Yes. You need a place where you can map names/emails to registration IDs. The inclusion of registration ID is a must and needs to be included while requesting FCM. E.g.

‘registration_ids’: [‘qrgqry34562456’, ‘245346236ef’], 

‘notification’: { 

‘body’: ”, 

‘title’: ” 

}, 

‘data’: { 

}

will send the push to ‘qrgqry34562456’ and ‘245346236ef’.

The registration ID used in the call is called ‘token’.

public class MyService extends FirebaseInstanceIdService { 

@Override public void onTokenRefresh() { 

}

Using the code mentioned below you can send messages to the other device without an issue.

public String send(String to, String body) {

 try { 

final String apiKey = “AIzaSyBsY_tfxxxxxxxxxxxxxxx”;

 URL url = new URL(“https://fcm.googleapis.com/fcm/send”); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod(“POST”); conn.setRequestProperty(“Content-Type”, “application/json”); conn.setRequestProperty(“Authorization”, “key=” + apiKey); conn.setDoOutput(true); JSONObject message = new JSONObject(); message.put(“to”, to); 

message.put(“priority”, “high”); 

JSONObject notification = new JSONObject(); 

// notification.put(“title”, title); 

notification.put(“body”, body); 

message.put(“data”, notification); 

OutputStream os = conn.getOutputStream(); os.write(message.toString().getBytes()); 

os.flush(); 

os.close(); 

int responseCode = conn.getResponseCode(); System.out.println(“\nSending ‘POST’ request to URL : ” + url); System.out.println(“Post parameters : ” + message.toString()); System.out.println(“Response Code : ” + responseCode); System.out.println(“Response Code : ” + conn.getResponseMessage()); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 

String inputLine; 

StringBuffer response = new StringBuffer(); 

while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result System.out.println(response.toString()); return response.toString(); } catch (Exception e) { e.printStackTrace(); } return “error”; }

Working Of Android Firebase Push Notification With Custom Click Action Simplified!

Many of you might wanna know the answer to the query mentioned in the heading. However, you’ll be unable to send a notification like that. In that case, you can use the code mentioned below. 

You gotta proceed to add intent_filter to the activity at the manifest.xml

<activity android:name=”.MyActivity”> 

<intent-filter> 

<action android:name=”com.mypackage.MyActivty_TARGET” /> 

<category android:name=”android.intent.category.DEFAULT”/> </intent-filter>

</activity>

Proceed to put click_action value as activity action: com.mypackage.MyActivty_TARGET”

and 

You’ll read the data from Android like :

String click_action = remoteMessage.getNotification().getClickAction(); Intent in = new Intent(click_action);

You can consider the code mentioned above to be an Android push notification tutorial. This will help you bypassing custom click action and performing the task that you intend to.

Thoughts Summed Up!

The blog above gives you a complete step-by-step process about the implementation of firebase push notification. This will help you in understanding the nitty-gritty that involves push notification challenges.

Images loaded with infographics and screenshots will give you how to go about the process. This will lead to a better implementation of the solution to the challenge that’s troubling you.

In a nutshell, the query, how to implement Firebase Push Notification in your Android by giving concise yet exhaustive details.


Sitaram Sharma
Sitaram Sharma

Co-Founder and VP Mobile Architect of Appventurez. A software professional who is highly experienced in Android, Flutter, React Native. He is a passionate developer with excellent programming skill who believes in bridging the technology gap and making the life of a large number of people much easier through his wide knowledge and experience.

⚡️ by Appventurez

Leave a Reply

Please rate*

Your email address will not be published.

Hey there! This is Sitaram, author of this blog. Leave your email address and we'll keep you posted on what we're up to.

This will subscribe you to Appventurez once-a-month newsletter. You can unsubscribe anytime. And we promise not to pester you or share your data :)

Hey there, wondering where this article came from? It was produced by some people at Appventurez, a Mobile & Web App Development Company. We are here for solutioning of your technological needs.

Our Latest Blog

How Buy Now Pay Later Apps Are Expanding Their Coverage In The US Market?

In the financial sector, buy now pay later(BNPL) has become a hot topic. In Jan...

Read more
a perfect tech stack for a digital startup
Perfect Tech Stack For A Digital Start-up

Do you know why giant tech businesses such as Netflix, Snapchat, Airbnb & P...

Read more
how to save your business covid with mobile app
How To Save Your Business Post-Covid With A Well-developed Mobile App?

The outbreak of COVID-19 was an unstoppable massacre not only for the human rac...

Read more

We’re your neighbor

Appventurez is a well known mobile app development company in the USA and India that works to build strong, long-lasting relations with its clients in different locations.

india flag appventurez
India (HQ)

Logix Infotech Park, 1st Floor, Plot No. D-5, Sector 59, Noida, Uttar Pradesh 201301

Inquiries : +91-9899 650980

5 Taunton Place Craigieburn VIC Australia

Inquiries : +1-815-283-8355

Office #216 Regus Tower Bank Street, Doha Qatar

Inquiries : +974-33497259

usa flag appventurez
USA

12501 W Chandler Blvd, Suite 200 Valley Village, CA 91607 USA

Inquiries : +1-888-822-1022

Rimal 5 Jumeirah Beach Residence 2 Dubai

Inquiries : +1-815-283-8355

south africa flag appventurez
South Africa

3 monterrey Complex, 63 Montrose Avenue, Northgate, Johannesburg, 2191

Inquiries : +27 737 810 945

7 Hanover House, Chapel Street, Bradford BD1 5DQ, United Kingdom

Inquiries : +1-815-283-8355

Netherlands flag appventurez
Netherlands

Amstelveen, Netherlands

Inquiries : +31-(0)-61-020-9692

Calle Ambar 2711, Av Victoria, 45089, Zapopan, Jalisco, Mexico

Inquiries : +521 332 393 9998

ghana flag appventurez
Ghana

North Industrial Area, Otublohum Road, Opposite Melcom Plus, Accra, Ghana

Inquiries : +27 737 810 945

appventurez worldwide presence
india flag appventurez
India (HQ)

Logix Infotech Park, 1st Floor, Plot No. D-5, Sector 59, Noida, Uttar Pradesh 201301

Inquiries : +91-9899 650980

5 Taunton Place Craigieburn VIC Australia

Inquiries : +1-815-283-8355

Office #216 Regus Tower Bank Street, Doha Qatar

Inquiries : +974-33497259

usa flag appventurez
USA

12501 W Chandler Blvd, Suite 200 Valley Village, CA 91607 USA

Inquiries : +1-888-822-1022

Rimal 5 Jumeirah Beach Residence 2 Dubai

Inquiries : +1-815-283-8355

south africa flag appventurez
South Africa

3 monterrey Complex, 63 Montrose Avenue, Northgate, Johannesburg, 2191

Inquiries : +27 737 810 945

7 Hanover House, Chapel Street, Bradford BD1 5DQ, United Kingdom

Inquiries : +1-815-283-8355

Netherlands flag appventurez
Netherlands

Amstelveen, Netherlands

Inquiries : +31-(0)-61-020-9692

Calle Ambar 2711, Av Victoria, 45089, Zapopan, Jalisco, Mexico

Inquiries : +521 332 393 9998

ghana flag appventurez
Ghana

North Industrial Area, Otublohum Road, Opposite Melcom Plus, Accra, Ghana

Inquiries : +27 737 810 945

10 Global Offices

Across 124 territories and 33.6k global workspace

700+ Worldwide clients

Largest International clients

24 x 7 Availability

Effective support, anytime