小编典典

Firebase Java Server将推送通知发送到所有设备

java

我正在尝试使用新的Firebase服务向我的android设备发送推送通知。我注册并设置了一个应用程序,然后将接收通知所需的所有代码都放入了android应用程序中。通过Firebase控制台,我可以将通知发送到我的应用程序,它会被接收并显示。现在,我想编写一个Java独立服务器,向所有设备发送通知。这是我当前的代码:

final String apiKey = "I added my key here";
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);

String input = "{\"notification\" : {\"title\" : \"Test\"}, \"to\":\"test\"}";

OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
os.close();

int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + input);
System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();

// print result
System.out.println(response.toString());

这就是我从他们的服务器找回来的结果:

{"multicast_id":6602141464107786356,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

不幸的是,简单地删除“
to”标签不起作用,然后我得到了返回的代码400。我读到我需要注册设备,将设备ID发送到服务器并保存在服务器上,然后遍历服务器上所有已注册的设备以发送消息。有没有更简单的方法,就像在控制台中一样,仅向所有设备发送消息?

非常感谢您的帮助,因为我一直在努力使它整日工作=(

问候,达斯汀


阅读 144

收藏
2020-11-13

共1个答案

小编典典

我认为这是不可能的。相反,我建议将所有设备注册到同一主题,然后您可以一次向所有设备发送消息。这是关于此的帮助文档:

从服务器发送主题消息

https://firebase.google.com/docs/cloud-messaging/topic-
messaging

2020-11-13