Send push notifications from server with FCM

后端 未结 6 933
滥情空心
滥情空心 2020-11-28 06:46

Recently I asked a question on sending push notifications using GCM: Send push notifications to Android. Now that there is FCM, I am wondering how different it would be from

6条回答
  •  攒了一身酷
    2020-11-28 07:02

    FULL SOLUTION FOR TOPIC, SINGLE DEVICE AND MULTIPLE DEVICES Create a class FireMessage. This is an example for data messages. You can change data to notification.

    public class FireMessage {
    private final String SERVER_KEY = "YOUR SERVER KEY";
    private final String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
    private JSONObject root;
    
    public FireMessage(String title, String message) throws JSONException {
        root = new JSONObject();
        JSONObject data = new JSONObject();
        data.put("title", title);
        data.put("message", message);
        root.put("data", data);
    }
    
    
    public String sendToTopic(String topic) throws Exception { //SEND TO TOPIC
        System.out.println("Send to Topic");
        root.put("condition", "'"+topic+"' in topics");
        return sendPushNotification(true);
    }
    
    public String sendToGroup(JSONArray mobileTokens) throws Exception { // SEND TO GROUP OF PHONES - ARRAY OF TOKENS
        root.put("registration_ids", mobileTokens);
        return sendPushNotification(false);
    }
    
    public String sendToToken(String token) throws Exception {//SEND MESSAGE TO SINGLE MOBILE - TO TOKEN
        root.put("to", token);
        return sendPushNotification(false);
    }
    
    
    
        private String sendPushNotification(boolean toTopic)  throws Exception {
            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("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
    
            System.out.println(root.toString());
    
            try {
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(root.toString());
                wr.flush();
    
                BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream())));
    
                String output;
                StringBuilder builder = new StringBuilder();
                while ((output = br.readLine()) != null) {
                    builder.append(output);
                }
                System.out.println(builder);
                String result = builder.toString();
    
                JSONObject obj = new JSONObject(result);
    
                if(toTopic){
                    if(obj.has("message_id")){
                        return  "SUCCESS";
                    }
               } else {
                int success = Integer.parseInt(obj.getString("success"));
                if (success > 0) {
                    return "SUCCESS";
                }
            }
    
                return builder.toString();
            } catch (Exception e) {
                e.printStackTrace();
               return e.getMessage();
            }
    
        }
    

    }

    And call anywhere like this. Both server and android we can use this.

    FireMessage f = new FireMessage("MY TITLE", "TEST MESSAGE");
    
          //TO SINGLE DEVICE
        /*  String fireBaseToken="c2N_8u1leLY:APA91bFBNFYDARLWC74QmCwziX-YQ68dKLNRyVjE6_sg3zs-dPQRdl1QU9X6p8SkYNN4Zl7y-yxBX5uU0KEKJlam7t7MiKkPErH39iyiHcgBvazffnm6BsKjRCsKf70DE5tS9rIp_HCk";
           f.sendToToken(fireBaseToken); */
    
        // TO MULTIPLE DEVICE
        /*  JSONArray tokens = new JSONArray();
          tokens.put("c2N_8u1leLY:APA91bFBNFYDARLWC74QmCwziX-YQ68dKLNRyVjE6_sg3zs-dPQRdl1QU9X6p8SkYNN4Zl7y-yxBX5uU0KEKJlam7t7MiKkPErH39iyiHcgBvazffnm6BsKjRCsKf70DE5tS9rIp_HCk");
          tokens.put("c2R_8u1leLY:APA91bFBNFYDARLWC74QmCwziX-YQ68dKLNRyVjE6_sg3zs-dPQRdl1QU9X6p8SkYNN4Zl7y-yxBX5uU0KEKJlam7t7MiKkPErH39iyiHcgBvazffnm6BsKjRCsKf70DE5tS9rIp_HCk");
           f.sendToGroup(tokens);  */
    
        //TO TOPIC
          String topic="yourTopicName";
           f.sendToTopic(topic); 
    

提交回复
热议问题