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

2022-09-01 21:41:25

我正在尝试使用新的 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发送到服务器并将其保存在那里,然后遍历服务器上的所有已注册设备以发送消息。难道没有一种更简单的方法,只需向所有设备发送消息,就像在控制台中一样吗?

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

问候, 达斯汀


答案 1

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

从服务器发送主题消息

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


答案 2

此解决方案使用 Apache HttpClient 向 Firebase 发送推送通知:

HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("https://fcm.googleapis.com/fcm/send");
post.setHeader("Content-type", "application/json");
post.setHeader("Authorization", "key=AIzaSyBSxxxxsXevRq0trDbA9mhnY_2jqMoeChA");

JSONObject message = new JSONObject();
message.put("to", "dBbB2BFT-VY:APA91bHrvgfXbZa-K5eg9vVdUkIsHbMxxxxxc8dBAvoH_3ZtaahVVeMXP7Bm0iera5s37ChHmAVh29P8aAVa8HF0I0goZKPYdGT6lNl4MXN0na7xbmvF25c4ZLl0JkCDm_saXb51Vrte");
message.put("priority", "high");

JSONObject notification = new JSONObject();
notification.put("title", "Java");
notification.put("body", "Notificação do Java");

message.put("notification", notification);

post.setEntity(new StringEntity(message.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
System.out.println(response);
System.out.println(message);

推荐