Anroid push notifications , fcm

By Алмас Абдразак

I’m develop java rest api service and i need to make push notifications to anroid devices. I’m not really sure how to do it properly, my code is

public class FcmNotif {
    public final static String AUTH_KEY_FCM = "My key";
    public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
// userDeviceIdKey is the device id you will query from your database
    public void pushFCMNotification(String userDeviceIdKey, String title, String message) 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.addProperty("to", userDeviceIdKey.trim());
        JsonObject info = new JsonObject();
        info.addProperty("title", title); // Notification title
        info.addProperty("body", message); // Notification body
        info.addProperty("image", "https://lh6.googleusercontent.com/-sYITU_cFMVg/AAAAAAAAAAI/AAAAAAAAABM/JmQNdKRPSBg/photo.jpg");
        info.addProperty("type", "message");
        json.add("data", info);
        System.out.println(json.toString());
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(json.toString());
        wr.flush();
        conn.getInputStream();
       // System.out.println(url.getH);
    }
    public static void main(String[] args) throws Exception {
        FcmNotif fcmN=new FcmNotif();
        fcmN.pushFCMNotification("user id ", "myFirstMessage", "hello");
        System.out.println("Done");
    }
}

AUTH_KEY_FCM i get from https://developers.google.com/mobile/add “Server API Key” and userDeviceIdKey its id that i get from running this code in android studio

String android_id = Settings.Secure.getString(getApplicationContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);

Maybe i don’t understand smth clearly, whan am i doing wrong?

Source: Stack Overflow

    

Share it with your friends!

    Fatal error: Uncaught Exception: 12: REST API is deprecated for versions v2.1 and higher (12) thrown in /home/content/19/9652219/html/wp-content/plugins/seo-facebook-comments/facebook/base_facebook.php on line 1273