37

Recently I asked a question on sending push notifications using GCM: Send push notifications to Android. Now that there is FCM, I am wondering how different it would be from the server side development. Coding wise, are they the same? Where can I find example FCM codes showing sending push notifications from server to Android device?

Do I need to download any JAR library for sending notifications to FCM using Java codes? The example codes in Send push notifications to Android shows sending push notifications using GCM and a server side GCM JAR file is required.

However, another example in https://www.quora.com/How-do-I-make-a-post-request-to-a-GCM-server-in-Java-to-push-a-notification-to-the-client-app shows sending push notifications using GCM and no server side GCM JAR file is required since it is just sending via an HTTP connection. Can the same codes be used for FCM? The URL used is "https://android.googleapis.com/gcm/send". What would be the equivalent URL for FCM?

Thanks in advance.

Community
  • 1
  • 1
user3573403
  • 1,558
  • 1
  • 29
  • 52
  • Have you gone to the FCM website, there is a step by step way of converting you current GCM project to FCM. – MNM May 30 '16 at 02:29
  • I currently don't have any push notification codes, such as GCM, yet. I am still researching the technologies behind the push notifications. – user3573403 May 30 '16 at 02:59
  • Read this blogpost for more details. http://developine.com/how-to-send-firebase-push-notifications-from-app-server-tutorial/ – Developine Nov 16 '17 at 07:43

6 Answers6

34

How different is server-side coding?

Since there is not much difference, you can just check out most of the example server-side codes for GCM as well. Main difference with regards to GCM and FCM is that when using FCM, you can use the new features with it (as mentioned in this answer). FCM also has a Console where you can send the Message/Notification from, without having your own app server.

NOTE: Creating your own app server is up to you. Just stating that you can send a message/notification via the console.

The URL used is "https://android.googleapis.com/gcm/send". What would be the equivalent URL for FCM?

The equivalent URL for FCM is https://fcm.googleapis.com/fcm/send. You can check out the this doc for more details.

Cheers! :D

Community
  • 1
  • 1
AL.
  • 33,241
  • 9
  • 119
  • 257
  • 1
    Hi McAwesomville, thanks for your reply. It seems that we don't really need additional library JAR file for sending notifications with either GCM or FCM. We can't just send an HTTP post with the required data to the GCM/FCM server. – user3573403 May 30 '16 at 05:55
  • 1
    Yep. No need for a JAR. Forgot to include that in my answer. Cheers! – AL. May 30 '16 at 05:57
  • Guys read this blogpost for more details.. http://developine.com/how-to-send-firebase-push-notifications-from-app-server-tutorial/ – Developine Nov 16 '17 at 07:43
  • If my server point to FCM Endpoint(GCM Cloud Project not convert to FireBase project), but push use old GCM API Key, the old client app push still work, right ? – Chris Ho Feb 12 '19 at 05:55
22

Use below code to send push notification from FCM server :

public class PushNotifictionHelper {
    public final static String AUTH_KEY_FCM = "Your api key";
    public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";

    public static String sendPushNotification(String deviceToken)
            throws IOException {
        String result = "";
        URL url = new URL(API_URL_FCM);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "key=" + AUTH_KEY_FCM);
        conn.setRequestProperty("Content-Type", "application/json");

        JSONObject json = new JSONObject();

        json.put("to", deviceToken.trim());
        JSONObject info = new JSONObject();
        info.put("title", "notification title"); // Notification title
        info.put("body", "message body"); // Notification
                                                                // body
        json.put("notification", info);
        try {
            OutputStreamWriter wr = new OutputStreamWriter(
                    conn.getOutputStream());
            wr.write(json.toString());
            wr.flush();

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            result = CommonConstants.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            result = CommonConstants.FAILURE;
        }
        System.out.println("GCM Notification is sent successfully");

        return result;

}
Morteza Jalambadani
  • 1,881
  • 5
  • 19
  • 30
Sandip S.
  • 510
  • 7
  • 10
1

This is coming straight from Google

You won’t need to make any server-side protocol changes for the upgrade. The service protocol has not changed. However, note that all new server enhancements will be documented in FCM server documentation.

And from receiving messages it seams there is only some places where its only slightly different. Mainly deleting somethings.

And the FCM server documentation can be found here https://firebase.google.com/docs/cloud-messaging/server

MNM
  • 2,387
  • 4
  • 34
  • 62
1

FULL SOLUTION FOR TOPIC, SINGLE DEVICE AND MULTIPLE DEVICES Create a class FireMessage. This is an example for data messages. You can change data to notification.

public class FireMessage {
private final String SERVER_KEY = "YOUR SERVER KEY";
private final String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
private JSONObject root;

public FireMessage(String title, String message) throws JSONException {
    root = new JSONObject();
    JSONObject data = new JSONObject();
    data.put("title", title);
    data.put("message", message);
    root.put("data", data);
}


public String sendToTopic(String topic) throws Exception { //SEND TO TOPIC
    System.out.println("Send to Topic");
    root.put("condition", "'"+topic+"' in topics");
    return sendPushNotification(true);
}

public String sendToGroup(JSONArray mobileTokens) throws Exception { // SEND TO GROUP OF PHONES - ARRAY OF TOKENS
    root.put("registration_ids", mobileTokens);
    return sendPushNotification(false);
}

public String sendToToken(String token) throws Exception {//SEND MESSAGE TO SINGLE MOBILE - TO TOKEN
    root.put("to", token);
    return sendPushNotification(false);
}



    private String sendPushNotification(boolean toTopic)  throws Exception {
        URL url = new URL(API_URL_FCM);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");

        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);

        System.out.println(root.toString());

        try {
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(root.toString());
            wr.flush();

            BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream())));

            String output;
            StringBuilder builder = new StringBuilder();
            while ((output = br.readLine()) != null) {
                builder.append(output);
            }
            System.out.println(builder);
            String result = builder.toString();

            JSONObject obj = new JSONObject(result);

            if(toTopic){
                if(obj.has("message_id")){
                    return  "SUCCESS";
                }
           } else {
            int success = Integer.parseInt(obj.getString("success"));
            if (success > 0) {
                return "SUCCESS";
            }
        }

            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
           return e.getMessage();
        }

    }

}

And call anywhere like this. Both server and android we can use this.

FireMessage f = new FireMessage("MY TITLE", "TEST MESSAGE");

      //TO SINGLE DEVICE
    /*  String fireBaseToken="c2N_8u1leLY:APA91bFBNFYDARLWC74QmCwziX-YQ68dKLNRyVjE6_sg3zs-dPQRdl1QU9X6p8SkYNN4Zl7y-yxBX5uU0KEKJlam7t7MiKkPErH39iyiHcgBvazffnm6BsKjRCsKf70DE5tS9rIp_HCk";
       f.sendToToken(fireBaseToken); */

    // TO MULTIPLE DEVICE
    /*  JSONArray tokens = new JSONArray();
      tokens.put("c2N_8u1leLY:APA91bFBNFYDARLWC74QmCwziX-YQ68dKLNRyVjE6_sg3zs-dPQRdl1QU9X6p8SkYNN4Zl7y-yxBX5uU0KEKJlam7t7MiKkPErH39iyiHcgBvazffnm6BsKjRCsKf70DE5tS9rIp_HCk");
      tokens.put("c2R_8u1leLY:APA91bFBNFYDARLWC74QmCwziX-YQ68dKLNRyVjE6_sg3zs-dPQRdl1QU9X6p8SkYNN4Zl7y-yxBX5uU0KEKJlam7t7MiKkPErH39iyiHcgBvazffnm6BsKjRCsKf70DE5tS9rIp_HCk");
       f.sendToGroup(tokens);  */

    //TO TOPIC
      String topic="yourTopicName";
       f.sendToTopic(topic); 
REMITH
  • 754
  • 7
  • 12
0

I have created a lib for FCM notification Server. Just use it like GCM lib.

For FCM Server use this code :

GCM Server URL-"android.googleapis.com/gcm/send"

FCM Server URL - "fcm.googleapis.com/fcm/send"

Append https with URL

Sender objSender = new Sender(gAPIKey);

or

Sender objSender = new Sender(gAPIKey,"SERVER_URL");

by DEFAULT FCM SERVER URL IS ASSIGNED

Message objMessage = new Message.Builder().collapseKey("From FCMServer").timeToLive(3).delayWhileIdle(false)
                .notification(notification)
                .addData("ShortMessage", "Sh").addData("LongMessage", "Long ")
                .build();
        objMulticastResult = objSender.send(objMessage,clientId, 4);
  • Dependency need for this lib is same like GCM lib required (jsonsimple.jar).

  • Download lib from FCM_Server.jar

Agilanbu
  • 2,308
  • 1
  • 26
  • 29
Sumit Kumar
  • 229
  • 1
  • 6
0
public class SendPushNotification extends AsyncTask<Void, Void, Void> {

    private final String FIREBASE_URL = "https://fcm.googleapis.com/fcm/send";
    private final String SERVER_KEY = "REPLACE_YOUR_SERVER_KEY";
    private Context context;
    private String token;

    public SendPushNotification(Context context, String token) {
        this.context = context;
        this.token = token;
    }

    @Override
    protected Void doInBackground(Void... voids) {

        /*{
            "to": "DEVICE_TOKEN",
            "data": {
            "type": "type",
                "title": "Android",
                "message": "Push Notification",
                "data": {
                    "key": "Extra data"
                }
            }
        }*/

        try {
            URL url = new URL(FIREBASE_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Authorization", "key=" + SERVER_KEY);

            JSONObject root = new JSONObject();
            root.put("to", token);

            JSONObject data = new JSONObject();
            data.put("type", "type");
            data.put("title", "Android");
            data.put("message", "Push Notification");

            JSONObject innerData = new JSONObject();
            innerData.put("key", "Extra data");

            data.put("data", innerData);
            root.put("data", data);
            Log.e("PushNotification", "Data Format: " + root.toString());

            try {
                OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
                writer.write(root.toString());
                writer.flush();
                writer.close();

                int responseCode = connection.getResponseCode();
                Log.e("PushNotification", "Request Code: " + responseCode);

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((connection.getInputStream())));
                String output;
                StringBuilder builder = new StringBuilder();
                while ((output = bufferedReader.readLine()) != null) {
                    builder.append(output);
                }
                bufferedReader.close();
                String result = builder.toString();
                Log.e("PushNotification", "Result JSON: " + result);
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("PushNotification", "Error: " + e.getMessage());
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.e("PushNotification", "Error: " + e.getMessage());
        }

        return null;
    }
}

Use

SendPushNotification sendPushNotification = new SendPushNotification(context, "token");
sendPushNotification.execute();
Ketan Ramani
  • 3,300
  • 24
  • 36