0

I am trying to make a chatting app in android studio. All the basic functions are done but I have been struggling with a problem for a time. The problem is sending notification to a device. I have searched the web a lot and was finally successful when a error came by the code is given below.

sendNotification function

private void sendNoti(String senderId, String receiverId){
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("to", "/User/"+receiverId);
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("title", "Message from " + senderId);
                jsonObject1.put("body", "hello");

                jsonObject.put("notification", jsonObject1);
                JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.e("SUCCESS", response + "");
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("ERRORS", error + "");
                    }
                }) {
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String, String> map = new HashMap<>();
                        map.put("content-type", "application/json");
                        map.put("authorization", "key=key");
                        Log.d("Maping",map.toString());
                        return map;
                    }
                };
                RequestQueue requestQueue = Volley.newRequestQueue(this);
                int socketTimeout = 1000 * 60;// 60 seconds
                RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
                request.setRetryPolicy(policy);
                requestQueue.add(request);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(@NonNull @NotNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        sendNotification(remoteMessage);

    }
    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("newToken", s);
        getSharedPreferences("_", MODE_PRIVATE).edit().putString("fb", s).apply();
        System.out.println("Token "+s);
    }

    private void sendNotification(RemoteMessage remoteMessage) {
        String user = remoteMessage.getData().get("from");
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");
        System.out.println("user "+user);
        System.out.println("title "+title);
        System.out.println("body "+body);

        Intent intent = new Intent(this, MainActivity.class);
        String channel_id = "notification_channel";
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        NotificationCompat.Builder builder = new NotificationCompat
                .Builder(getApplicationContext(), channel_id)
                .setSmallIcon(R.drawable.vroo)
                .setContentTitle(title)
                .setContentText("body")
                .setAutoCancel(true)
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
                .setOnlyAlertOnce(true)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(channel_id, "web_app", NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(notificationChannel);
        }

        notificationManager.notify(0, builder.build());

    }
}

I get the log output that my message is sent but I never receive it on the receiver side can someone please help me?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
JashSmith
  • 211
  • 1
  • 15
  • 1
    *firebaser here* Calls to the FCM REST API require that you pass the FCM *server** key in the `authorization` header 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 Jul 31 '21 at 14:54
  • @FrankvanPuffelen hey thanks for your responce, I solved the issue yay! the problem was that I did not subscribe the topic the notificationwas sent to. – JashSmith Jul 31 '21 at 17:25

0 Answers0