0

I am new in Android development and I am trying to work on a project which involves an application that uses Firebase database. I want to send notifications to users when something happens, i.e. when I assign a task to a user.

I have implemented necessary Firebase classes and I can successfully send notifications to users, using their token from Firebase console. However, I can't manage to send custom notifications from the code in Android Studio.

I have tried the following function and I am passing the token of a device plus a title and a body for the notification and it's not working.

public static void pushFCMNotification(String userDeviceIdKey, String title, String body) throws     Exception{

    String authKey = AUTH_KEY_FCM;   // You FCM AUTH key
    String FMCurl = API_URL_FCM;
    URL url = new URL(FMCurl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setUseCaches(false);
    conn.setDoInput(true);
    conn.setDoOutput(true);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization","key="+authKey);
    conn.setRequestProperty("Content-Type","application/json");

    JSONObject json = new JSONObject();
    json.put("to",userDeviceIdKey);
    JSONObject info = new JSONObject();
    info.put("title", title);   // Notification title
    info.put("body", body); // Notification body
    json.put("notification", info);

    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(json.toString());
    wr.flush();
    conn.getInputStream();
}

Can someone give me some guidelines or any other ways of implementing such notifications?

AL.
  • 36,815
  • 10
  • 142
  • 281
  • everything looks good. Please check your AUTH_KEY_FCM. see my answer here for the same problem http://stackoverflow.com/questions/37435750/how-to-send-device-to-device-messages-using-firebase-cloud-messaging/41982419#41982419 – Brijesh Kumar Mar 08 '17 at 17:04
  • Thanks for your answer, I'll have a look at this.When going into the cloud messaging settings there's a Server Key and a Legacy Server Key. I am using the Server key, is that right? – Alexia Haralambous Mar 08 '17 at 18:42
  • For Authorization FCM notification use Legacy Server Key. – eurosecom Mar 08 '17 at 21:31
  • Hi Alexia. Sending a message originating from the client (Android) app is *strongly* **not** advised. Since doing so would require you to put the *Server Key* in your code, exposing it to others that may exploit it. As the name implies, it should be kept only in a secure server of your choice. – AL. Mar 09 '17 at 03:14
  • @eurosecom Using the *Server Key* instead of the *Legacy* Server key is recommended. A note is already visible in the Firebase Console (emphasis mine*: "*Firebase has upgraded our server keys to a new version. You may continue to use your Legacy server key, **but we recommend that you upgrade to the newest version**.*" – AL. Mar 09 '17 at 03:16

0 Answers0