Android notifications from a Java server

With the following script, youll be able to send push notifications to Android devices from a Java server, without implementing any of the Firebase frameworks to keep your server tidy and less cluttered.

I will asume that you already got, somehow, the tokens for each device and that you already got the server key after setting up your project in the Firebase Console.

 

public class NotificationManager {

    public sendNotification(){
        ArrayList<String> tokens = new ArrayList<String>();
        tokens.add("token_for_device_1");
        tokens.add("token_for_device_2");
        tokens.add("token_for_device_3");
        
        String title = "This is a notification";
        String message = "This is the notification message";
        String extradata = "2020-01-01";

        String jsondata = "{\"title\": \"" + title +
                        "\", \"message\": \"" + message +
                        "\", \"extradata\": \"" + extradata +
                        "\"}";
//You can add as many parameters as you like to the jasondata

        if(tokens.size() > 0){
            NotifyAndroid notifyAndroid = new NotifyAndroid(tokens, jsondata) ;
            Thread t = new Thread(notifyAndroid);
            t.start();
        }
    }

    class NotifyAndroid implements Runnable {
        String jsonTokens;
        String jsonData;

        public NotifyAndroid(ArrayList<String> tokens, String jsonData) {
            
            this.jsonData = jsonData;
            this.jsonTokens = "[";
            for(String token: tokens){ this.jsonTokens+="\""+token+"\","; }
            this.jsonTokens.substring(0, this.jsonTokens.length() - 1);
            this.jsonTokens+="]";
        }

        public void run() {
            try {
                byte[] postdata  = ("{\"registration_ids\":"+jsonTokens+",\"data\":"+jsonData+"}").getBytes(StandardCharsets.UTF_8);

                URL url = new URL("https://fcm.googleapis.com/fcm/send");
                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                c.setDoOutput(true);
                c.setRequestMethod("POST");
                c.setRequestProperty("Authorization","key=<HERE GOES YOUR SERVER KEY>");
                c.setRequestProperty("Content-Type", "application/json");
                c.setRequestProperty("Content-Lenght",postdata.length +"");
                c.setUseCaches(false);

                OutputStream os = c.getOutputStream();
                os.write(postdata);
                os.flush();
                os.close();

//The following lines are only necessary if you need the response from Firebase to check if the notification was delivered or not
                int responseCode = c.getResponseCode();
                System.out.print(responseCode);
                BufferedReader in=new BufferedReader( new  InputStreamReader(c.getInputStream()));
                StringBuffer sb = new StringBuffer("");
                String line="";
                while((line = in.readLine()) != null) {
                    sb.append(line);
                    break;
                }
                in.close();
                System.out.print(sb.toString());
                

            }catch (Exception e){
                System.out.print(e.toString());
            }
        }
    }
}

 

 

Leave a Reply

Your email address will not be published.