How to send Firebase push notification to your Android or iOS client from application server example.

 

I will give you an example of How to send firebase push notification to Android or iOS devices from PHP, Java,  C# or using Rest Client.

Here is Rest API example which we will use to send notifications to our client application. You can implement this Rest API in your application server.

HTTP METHOD : POST

URL: https://fcm.googleapis.com/fcm/send

Header :

Content-Type: application/json

Authorization: Server Key

(e.g key=AIzaSyD_Vw3Zf8XXXSDMSDKLMGyqR_Kyw5o)

You can find Servery key under Settings >Cloud messaging > Server key

Body :

You can send two types of data in request body.

1. Notification payload. (if you send notification using firebase console. It also sends notification payload.

    Firebase SDK at client side do not handle or receive a push notification from the server.

    Instead, Notification is passed to the Android OS for displaying in the notification panel.)

2. Data payload. (If you want to handle notification in your client application you should send data payload)

You can read about the difference in notification payload and data payload from this tutorial.

We will send data payload as Notification data payload.

Body:

{ “data”: 
{
 “title”: “Firebase notification”,
 “detail”: “I am firebase notification. you can customise me. enjoy”,
 },
 “to” : “efaOvIXDbik:APA91bEkNUVWNaoA….”
 }

to = your application firebase token.

where to get this firebase token?

In Android Apps which handles firebase push notification.

•On Initial startup of the Project Application, Firebase SDK will generate a unique device token inside method onTokenRefreshed.

override onTokenRefreshed(String token) 
{
  // from here you can save application token in your app server.
}

will be called whenever a token is updated or generated.

And you have to save this token in your application server.

Above example is to send notification to single device.

Here is a rest client screenshot for more clarification.

Sending Firebase Push Notification from server

How to Send push notification to all users or multiple devices from server side?

We already discussed how to send a push notification to the single device.

There are 2 ways of sending push notification to all devices or users from your app server using FCM.

  1. Using all firebase token’s and put them in registration_ids array.

You have to pass firebase registration tokens in registration_ids Array.

     
{
"registration_ids": [
"eQX_V2DoMDU:APA91bED-PobAzyYrWP4I3VSLcL7-o1-RhaOk3L9gE",
"didwBCYh30E:APA91bh72X"
],
"priority": "high",

"data": {
"title": "Firebase Notification Example",
"detail": "This firebase push notification will be sent to all firebase tokens (devices) registered with your app server."
}
}

2. Topics

Now the second method is Topics.

  • Topics are just keys which users subscribe to. Users have to subscribe to any topic.
  • Users can subscribe to any existing topic or can create a new topic and than subscribe to it.

To subscribe to any topic. users/client use this code (this is Android Code)

FirebaseMessaging.getInstance().subscribeToTopic("anytopic");

HTTP POST REQUEST SAMPLE for send firebase push notification to all users who subscribed to news topic.

URL: https://gcm-http.googleapis.com/gcm/send
HEADER:
Content-Type:application/json
Authorization:key=AIswgdyZ-4f...0HPYzPDSKNSSaA
Body :
{
  "to": "/topics/news",
  "data": {
    "message": "This is a FCM Topic Message!",
}

You can implement this code in your application server.

Now all users/ devices who subscribed to  topic “news” topic will receive a push notification.

Now we will write Java client code which will send Firebase (FCM) Push Notification and you can use this code  example in your application server.

Firebase Cloud Messaging (FCM) JAVA SERVER SIDE CODE EXAMPLE

Step 1-

First of all, create a new project in your IDE (I used IntelliJ IDEA).

Step 2- Setup Gradle dependencies

Add below dependencies in your project.

  1. Javax Annotation
  2. Google Gson
  3. Apache HttpClient
group 'pushnotification'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile 'javax.annotation:javax.annotation-api:1.2'
    compile 'com.google.code.gson:gson:2.8.1'
    compile 'org.apache.httpcomponents:httpclient:4.5.4'

}

Step 3- Create Model / POJO classes for FCM Notification Data payload

import javax.annotation.Generated;
import com.google.gson.annotations.SerializedName;

@Generated("net.hexar.json2pojo")
@SuppressWarnings("unused")
public class NotificationData {

    @SerializedName("detail")
    private String mDetail;

    @SerializedName("title")
    private String mTitle;

    public String getDetail() {
        return mDetail;
    }

    public void setDetail(String detail) {
        mDetail = detail;
    }

    public String getTitle() {
        return mTitle;
    }

    public void setTitle(String title) {
        mTitle = title;
    }
}

And

import javax.annotation.Generated;
import com.google.gson.annotations.SerializedName;

@Generated("net.hexar.json2pojo")
@SuppressWarnings("unused")
public class NotificationRequestModel {

    @SerializedName("data")
    private NotificationData mData;
    @SerializedName("to")
    private String mTo;

    public NotificationData getData() {
        return mData;
    }

    public void setData(NotificationData data) {
        mData = data;
    }

    public String getTo() {
        return mTo;
    }

    public void setTo(String to) {
        mTo = to;
    }
}

 

Step 4- Sending Firebase Push Notifications API using Java Http Client

Create a new Application Class inside the main package of your project.

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import model.NotificationData;
import model.NotificationRequestModel;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.lang.reflect.Type;


public class ApplicationClass {


    public static void main(String[] args) throws IOException {

        System.out.println("Welcome to Developine");


        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(
                "https://fcm.googleapis.com/fcm/send");

        // we already created this model class.
        // we will convert this model class to json object using google gson library.

        NotificationRequestModel notificationRequestModel = new NotificationRequestModel();
        NotificationData notificationData = new NotificationData();

        notificationData.setDetail("this is firebase push notification from java client (server)");
        notificationData.setTitle("Hello Firebase Push Notification");
        notificationRequestModel.setData(notificationData);
        notificationRequestModel.setTo("eHp6V2Wtr4I:APA91bFLHRuScumQB0lnNRmeirxu5kV2lUPDZ8SbZKz");


        Gson gson = new Gson();
        Type type = new TypeToken<NotificationRequestModel>() {
        }.getType();

        String json = gson.toJson(notificationRequestModel, type);

        StringEntity input = new StringEntity(json);
        input.setContentType("application/json");

        // server key of your firebase project goes here in header field.
        // You can get it from firebase console.

        postRequest.addHeader("Authorization", "key=AAAA7-UgB34:APA91bFhpZ1-MYyFfQd2gof0vUAFKNcQCmmf_10acMn-HS_0iBBvP");
        postRequest.setEntity(input);

        System.out.println("reques:" + json);

        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        } else if (response.getStatusLine().getStatusCode() == 200) {

            System.out.println("response:" + EntityUtils.toString(response.getEntity()));
           
        }
    }
}

Simply Run this code and it will send Firebase Push Notification to your Android/iOS application using Firebase Server.

This will be the output of above Java code.

Welcome to Developine
request:{"data":{"detail":"this is firebase push notification from java client (server)","title":"Hello Firebase Push Notification"},"to":"eHp6V2Wtr4I:APA91b4tPNStf-vFTGNy8RSbZKz"}
response:{"multicast_id":6045444993562588493,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1515057939997633%6e39fd7ecd"}]}

I copied token of a single user manually and used in above code.

In a real-world project, you have to send Firebase token which is generated on the client side (Mobile App) to your application server.

Conclusion:-

We first learned how we can send Firebase push notification using Rest Client.

We also learned how to send Firebase Push Notification from java client using firebase server.

Recommended Reading:-

How to setup firebase push notification in Android

If this helped you share this article and subscribe to our website for latest updates on Kotlin, Android, Spring Boot.

https://github.com/hammad-tariq/firebase-push-notification-server-java-rest-client-example

Contact Us