39

最近我问了一个关于使用 GCM发送推送通知的问题:向 Android 发送推送通知。现在有了 FCM,我想知道它与服务器端开发有何不同。编码明智,它们是一样的吗?我在哪里可以找到显示从服务器向 Android 设备发送推送通知的示例 FCM 代码?

我是否需要下载任何 JAR 库才能使用 Java 代码向 FCM 发送通知?向 Android 发送推送通知中的示例代码显示使用 GCM 发送推送通知,并且需要服务器端 GCM JAR 文件。

但是,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显示使用 GCM 发送推送通知,并且不需要服务器端 GCM JAR 文件,因为它只是通过 HTTP 连接发送。FCM 可以使用相同的代码吗?使用的 URL 是“ https://android.googleapis.com/gcm/send ”。FCM 的等效 URL 是什么?

提前致谢。

4

6 回答 6

35

服务器端编码有何不同?

由于没有太大区别,您也可以查看 GCM 的大多数示例服务器端代码。GCM 和 FCM 的主要区别在于,在使用 FCM 时,您可以使用它的新功能(如本答案中所述)。FCM 还有一个控制台,您可以从中发送消息/通知,而无需拥有自己的应用服务器。

注意:创建自己的应用服务器取决于您。只是说明您可以通过控制台发送消息/通知。

使用的 URL 是“ https://android.googleapis.com/gcm/send ”。FCM 的等效 URL 是什么?

FCM 的等效 URL 是https://fcm.googleapis.com/fcm/send。您可以查看此文档以获取更多详细信息。

干杯! :D

于 2016-05-30T03:49:05.707 回答
23

使用以下代码从 FCM 服务器发送推送通知:

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;

}
于 2017-03-02T06:46:40.983 回答
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

于 2016-05-30T03:28:44.337 回答
1

主题、单个设备和多个设备的完整解决方案 创建一个 FireMessage 类。这是数据消息的示例。您可以将数据更改为通知。

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();
        }

    }

}

并像这样在任何地方打电话。server 和 android 我们都可以使用它。

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); 
于 2018-03-10T07:06:21.133 回答
0

我为FCM 通知服务器创建了一个库。就像GCM lib 一样使用它。

对于 FCM 服务器,请使用以下代码:

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

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

附加httpsURL

Sender objSender = new Sender(gAPIKey);

或者

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

默认 FCM 服务器 URL 已分配

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);
于 2017-07-06T04:53:28.357 回答
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;
    }
}

利用

SendPushNotification sendPushNotification = new SendPushNotification(context, "token");
sendPushNotification.execute();
于 2019-04-26T10:42:16.600 回答