FCM HTTP请求返回message_id,但Android设备未收到消息

7
我正在尝试将通知发送到我的安卓设备。我使用Firebase Cloud Messaging来发送通知。我可以通过Firebase控制台发送通知并在手机上收到消息。然而,我正在尝试通过我的服务器发送消息,但尚未成功。

当我执行下面的代码时,我会得到以下响应:

"{\"message_id\":58934758934758936346437}"

当我们查看Firebase文档Firebase Documentation时,可以看到接收到message_id意味着消息已经成功发送。但是,我没有在手机上收到它。

我已经订阅了正确的主题。

我正在运行以下代码:

private void test(String topic) {
    try {
        //Setup request
        URL url = new URL("https://fcm.googleapis.com/fcm/send");
        HttpURLConnection hc = (HttpURLConnection) url.openConnection();
        hc.setDoOutput(true);
        hc.setDoInput(true);

        //Set request params
        String message = "{\"to\": \"/topics/" + topic + "\"}";

        hc.addRequestProperty("Content-Type", "application/json");
        hc.addRequestProperty("Authorization", "key=SECRET");

        DataOutputStream dos = new DataOutputStream(hc.getOutputStream());
        dos.writeBytes(message);
        dos.close();

        //Get Response  
        InputStream is = hc.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
        String line;
        while ((line = rd.readLine()) != null) {
          response.append(line);
        }
        rd.close();

        label.setText("RESPONSE: " + response.toString());

    } catch (Exception ex) {
        label.setText("Er ging iets mis");
        ex.printStackTrace();
    }
}
1个回答

3
您的有效载荷不包含任何消息
String message = "{\"to\": \"/topics/" + topic + "\"}";

该消息仅包含接收者(to),没有实际的消息内容。您需要发送一个notificationdata消息负载。以下是示例:

String message = "{\"to\": \"/topics/" + topic + "\",
    \"notification\" : {
        \"title\" : \"sample title\",
        \"body\" : \"sample body\"
    }
}";

这里查看notificationdata的可用参数,并注意这两个消息负载的处理方式不同。有关详细信息,请参阅在 Android 中接收消息文档。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接