Firebase Java Server to send push notification to all devices

user3907491 picture user3907491 · Jun 1, 2016 · Viewed 65.4k times · Source

I am trying to send a Push notification to my android device with the new Firebase service. I registered and setup an app, also I put all the code needed to receive notification in the android app. Via the Firebase Console I can send a notification to my app and it is received and shown. Now I want to write a java standalone server, to send a notification to ALL devices. This is my current code:

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());

And this is the result that I am getting back from their servers:

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

Unfortunately, simply removing the "to" tag doesn't work, I am getting a code 400 returned then. I read that I need to register the device, send the device id to the server and save it there and then loop over all registered devices on the server to send the message. Isn't there an easier way, to just send a message to all devices, just like in the console?

Your help is really appreciated, since I have been trying to get this to work all day long =(

Regards, Dustin

Answer

Alexander N. picture Alexander N. · Jun 1, 2016

I don't believe this is possible. Instead, what I would suggest is register all devices to the same topic and then you can message all the devices at once. Here is the help documentation on this:

Send Topic Messages from the Server

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