我正在尝试使用新的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发送到服务器并将其保存在那里,然后遍历服务器上的所有已注册设备以发送消息.
是不是有一种更简单的方法,只需向所有设备发送消息,就像在控制台中一样?
非常感谢您的帮助,因为我一直试图让这一天全天工作=(
问候,
达斯汀