Easily Understand How to Send Notification in Android Using Firebase!

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

Updated 19 September 2023

One of the most asked queries by developers is how to send notifications in Android using Firebase. Over the years, the challenges faced by backend developers have been addressed by Firebase. It is known for providing push notification 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 with 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.

 Push Notification in Android Using Firebase – 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 notifications in the Android example which will clear your doubts.

Android Using Firebase

#1 – Application Server

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

#2 – Notification Server

The 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 the 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 notifications 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 “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, except 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 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’s 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 tokens 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 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 from a 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 concisely. 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 Google credentials = GoogleCredentials

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

    FirebaseOptions firebaseOptions = FirebaseOptions

            .builder()

            .setCredentials(google credentials)

            .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 send notification(Note note, String token) throws FirebaseMessagingException {

        Notification = Notification

                .builder()

                .setTitle(note.getSubject())

                .setBody(note.getContent())

                .build();

        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 send notification(@RequestBody Note note,

                               @RequestParam String token) throws FirebaseMessagingException {

    return firebase service.send notification(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 to 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 Notifications from Firebase Console? Check Out Below!

To get an understanding of how to send notifications 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.

  • If this is your first warning, you’ll see a “Send your first message” button. Snap it. 
  • If 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: if 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 focus 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 a ‘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 input line; 

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. package.MyActivty_TARGET” /> 

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

</activity>

Proceed to put click_action value as activity action: com. package.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 bypass custom click action and perform the task that you intend to.

Thoughts Summed Up!

The blog above gives you a complete step-by-step process for the implementation of Firebase push notifications. 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 is how to implement Firebase Push Notification in your Android by giving concise yet exhaustive details.

contact us if you want to resolve push notification issues in your android app

 


sitaram

Chief Technology Officer


Related Blogs

Top Android Frameworks For Mobile App Development In 2023

Read More

Android Go vs Regular Apps – Elaborating The Distinction

Read More

30+ Hacks of Android App Development

Read More

    I’m interested in