我正在尝试使用新的 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 发送到服务器并将其保存在那里,然后遍历服务器上所有已注册的设备以发送消息。有没有更简单的方法,就像在控制台中一样,向所有设备发送消息?
非常感谢您的帮助,因为我一整天都在努力让它工作 =(
问候,达斯汀
原文由 user3907491 发布,翻译遵循 CC BY-SA 4.0 许可协议
我不相信这是可能的。相反,我建议将所有设备注册到同一主题,然后您可以一次向所有设备发送消息。这是关于此的帮助文档:
从服务器发送主题消息
https://firebase.google.com/docs/cloud-messaging/topic-messaging