Rainer Lang Rainer Lang - 4 months ago 14
Android Question

GCM Push Notifications are not delivered to devices

We (Panos and Rainer - see the comments down) have a server and several Android devices.

We want to send push notifications from our server via GCM to the Android devices.

Now we make a post request to the GCM server. The GCM server response is that all is fine (success==1 and even the message-id)!
BUT the push notification(s) are never delivered to the devices.

If we use the same data and the Chrome addon Postman - the notifications are delivered immediately.

We tried all lot of different solutions. We get always the feedback of the GCM server that all is ok - but the push notifications aren't send.

We also tried this one:
https://github.com/googlesamples/google-services/blob/master/android/gcm/gcmsender/src/main/java/gcm/play/android/samples/com/gcmsender/GcmSender.java

Answer

You might also post the URL you use. There is a new GCM enpoint which looks like the following:

https://gcm-http.googleapis.com/gcm/send

I am not yet sure what's causing the issues on your side. But the following is tested and working:

public class Main {

    public static void main(String[] args) {
    // write your code here

        try {

            String url = "https://gcm-http.googleapis.com/gcm/send";

            URL obj = new URL(url);
            HttpsURLConnectionImpl conn = (HttpsURLConnectionImpl) obj.openConnection();


            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);

            conn.setRequestMethod("POST");
            conn.setRequestProperty ("Authorization", "key=***");

            String title = "Short title";
            String body = "A body :D";
            String token = "****";
            String data =  "{ \"notification\": { \"title\": \"" + title +"\", \"body\": \"" + body + "\" }, \"to\" : \"" + token + "\", \"priority\" : \"high\" }";
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
            out.write(data);
            out.close();

            String text = getText(new InputStreamReader(conn.getInputStream()));
            System.out.println(text);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getText(InputStreamReader in) throws IOException {
        StringBuilder sb=new StringBuilder();
        BufferedReader br = new BufferedReader(in);
        String read;
        while((read=br.readLine()) != null) {
            sb.append(read);
        }
        br.close();
        return sb.toString();
    }
}
Comments