0

My app crashed while trying to send fcm notifications to devices subcribed to a topic using android volley Json, Here is the code am using.

private void sendNotify()throws JSONException{
        rootObject = new JSONObject();
        JSONObject dataObject = new JSONObject();
        dataObject.put("message_title", "This is the Title");
        dataObject.put("message", "This is the Body Of The Message");
        dataObject.put("message_image_url", "https://www.image.com/image.jpg");
        String url0 = "https://fcm.googleapis.com/fcm/send";

        try{
            rootObject.put("data", dataObject);
            rootObject.put("to","/topics/DailyNotice");
        } catch (JSONException e){
            Toast.makeText(this, "Error 1"+e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        }
        StringRequest request = new StringRequest(Request.Method.POST, url0, response -> Toast.makeText(getApplicationContext(), "Response "+response, Toast.LENGTH_SHORT).show(), error -> {
            Toast.makeText(this, "Error 1"+error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        }){
            @Override
            public byte[] getBody() {
                return rootObject.toString().getBytes();
            }

            @Override
            public Map<String, String> getHeaders() {
                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                headers.put("Authorization", "key="+dKey);
                return headers;
            }
        } ;

        requestQueue.add(request);

    }

when i send using this above method i get this response string in toast >> {message_id:"some random numbers"}.

  • *firebaser here* It looks like you're calling the FCM REST API from within the Android app. Calls to the FCM REST API require that you specify the FCM *server** key in your code. As its name implies, this key should only be used in server-side code, or in an otherwise trusted environment. The reason for this is that anyone who has the FCM server key can send whatever message they want to all of your users. By including this key in your Android app, a malicious user can find it and you're putting your users at risk. See https://stackoverflow.com/a/37993724 for a better solution. – Frank van Puffelen Feb 19 '21 at 02:25
  • Thanks i have a server app both connected to the firebase project am using it to send the message to all other devices based on the topic subscribed to so only this app has the server key which i declare here `headers.put("Authorization", "key="+dKey);` the key string is declare in the activity – Serenity Emmanuel Feb 19 '21 at 02:31

0 Answers0