Send push notifications from server with FCM
How different is server-side coding?
Since there is not much difference, you can just check out most of the example server-side codes for GCM as well. Main difference with regards to GCM and FCM is that when using FCM, you can use the new features with it (as mentioned in this answer). FCM also has a Console where you can send the Message/Notification from, without having your own app server.
NOTE: Creating your own app server is up to you. Just stating that you can send a message/notification via the console.
The URL used is "https://android.googleapis.com/gcm/send". What would be the equivalent URL for FCM?
The equivalent URL for FCM is https://fcm.googleapis.com/fcm/send. You can check out the this doc for more details.
Cheers! :D
Use below code to send push notification from FCM server :
public class PushNotifictionHelper {
public final static String AUTH_KEY_FCM = "Your api key";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
public static String sendPushNotification(String deviceToken)
throws IOException {
String result = "";
URL url = new URL(API_URL_FCM);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "key=" + AUTH_KEY_FCM);
conn.setRequestProperty("Content-Type", "application/json");
JSONObject json = new JSONObject();
json.put("to", deviceToken.trim());
JSONObject info = new JSONObject();
info.put("title", "notification title"); // Notification title
info.put("body", "message body"); // Notification
// body
json.put("notification", info);
try {
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(json.toString());
wr.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
result = CommonConstants.SUCCESS;
} catch (Exception e) {
e.printStackTrace();
result = CommonConstants.FAILURE;
}
System.out.println("GCM Notification is sent successfully");
return result;
}