0

I am trying to send notification to a specific user using FCM token. When I send press the send notification button the notification is received in the same device from which it was sent and not to the device with the token. Here is my code

FirebaseMessagingService.java

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

     NotificationManager mNotificationManager;

    @Override
    public void onNewToken(@NonNull String s) {
        super.onNewToken(s);
        Log.d("token",s);
        SharedPreferences.Editor editor = getSharedPreferences("RegisteredToken", MODE_PRIVATE).edit();
        editor.putString("tokenName", s);
        editor.apply();
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);


// playing audio and vibration when user se reques
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        r.play();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            r.setLooping(false);
        }

        // vibration
        Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        long[] pattern = {100, 300, 300, 300};
        v.vibrate(pattern, -1);


        int resourceImage = getResources().getIdentifier(remoteMessage.getNotification().getIcon(), "drawable", getPackageName());



        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "CHANNEL_ID");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            builder.setSmallIcon(R.drawable.icontrans);
            builder.setSmallIcon(resourceImage);
        } else {
//            builder.setSmallIcon(R.drawable.icon_kritikar);
            builder.setSmallIcon(resourceImage);
        }



        Intent resultIntent = new Intent(this, TestingActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);


        builder.setContentTitle(remoteMessage.getNotification().getTitle());
        builder.setContentText(remoteMessage.getNotification().getBody());
        builder.setContentIntent(pendingIntent);
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()));
        builder.setAutoCancel(true);
        builder.setPriority(Notification.PRIORITY_MAX);

        mNotificationManager =
                (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);




        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            String channelId = "Your_channel_id";
            NotificationChannel channel = new NotificationChannel(
                    channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_HIGH);
            mNotificationManager.createNotificationChannel(channel);
            builder.setChannelId(channelId);
        }



// notificationId is a unique int for each notification that you must define
        mNotificationManager.notify(100, builder.build());


    }

FcmNotificationsSender.java

public class FcmNotificationsSender  {

    String userFcmToken;
    String title;
    String body;
    Context mContext;
    Activity mActivity;


    private RequestQueue requestQueue;
    private final String postUrl = "https://fcm.googleapis.com/fcm/send";
    private final String fcmServerKey ="AAAAy2VUhRs:APA91bFC2tO5CkLOlnZpRTgOsPt7jeo-OzYox0Jc3zwHhluOntpCD4TVknQemLzWOAdFlzDWUl4vf471lv7lM9AH9n6Y-7TyVRZD6u9COxSBwGS15P23xtlQ03WYOcCBUGnXrcTk8cwe";

    public FcmNotificationsSender(String userFcmToken, String title, String body, Context mContext, Activity mActivity) {
        this.userFcmToken = userFcmToken;
        this.title = title;
        this.body = body;
        this.mContext = mContext;
        this.mActivity = mActivity;


    }

    public void SendNotifications() {

        requestQueue = Volley.newRequestQueue(mActivity);
        JSONObject mainObj = new JSONObject();
        try {
            mainObj.put("to", userFcmToken);
            JSONObject notiObject = new JSONObject();
            notiObject.put("title", title);
            notiObject.put("body", body);
            notiObject.put("icon", "icon"); // enter icon that exists in drawable only



            mainObj.put("notification", notiObject);


            JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, postUrl, mainObj, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    // code run is got response

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // code run is got error

                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {

                    Map<String, String> header = new HashMap<>();
                    header.put("Content-Type", "application/json");
                    header.put("Authorization", "key=" + fcmServerKey);

                    /*Map<String, String> header = new HashMap<>();
                    header.put("content-type", "application/json");
                    header.put("authorization", "key=" + fcmServerKey);*/
                    return header;
                }
            };
            requestQueue.add(request);

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

TestingActivity.java

public class TestingActivity extends AppCompatActivity {

    EditText titleEt,messageEt,tokenEt;
    Button sendToAllBtn,sendToTokenBtn;
    String token = "tokenString";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testing);
        titleEt = findViewById(R.id.titleEt);
        messageEt = findViewById(R.id.messageEt);
        tokenEt = findViewById(R.id.tokenEt);
        sendToAllBtn = findViewById(R.id.sendToAllBtn);
        sendToTokenBtn = findViewById(R.id.sendToTokenBtn);

        FirebaseMessaging.getInstance().subscribeToTopic("all");
        SharedPreferences prefs = getSharedPreferences("RegisteredToken", MODE_PRIVATE);
        token = prefs.getString("tokenName", "");//"No name defined" is the default value.
        Toast.makeText(getApplicationContext(), ""+token, Toast.LENGTH_SHORT).show();
        Log.d("Token",token);



        sendToAllBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (titleEt.getText().toString().trim().isEmpty() || messageEt.getText().toString().trim().isEmpty()){
                    Toast.makeText(TestingActivity.this, "Pleas Fill Details", Toast.LENGTH_SHORT).show();
                } else {
                    FcmNotificationsSender notificationsSender = new FcmNotificationsSender("/topics/all",titleEt.getText().toString(),
                            messageEt.getText().toString(),getApplicationContext(),TestingActivity.this);
                    notificationsSender.SendNotifications();
                }
            }
        });

        sendToTokenBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (titleEt.getText().toString().trim().isEmpty() || messageEt.getText().toString().trim().isEmpty()){
                    Toast.makeText(TestingActivity.this, "Pleas Fill Details", Toast.LENGTH_SHORT).show();
                } else {
                    FcmNotificationsSender notificationsSender = new FcmNotificationsSender(token,titleEt.getText().toString(),
                            messageEt.getText().toString(),getApplicationContext(),TestingActivity.this);
                    notificationsSender.SendNotifications();
                }
            }
        });
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I have explained in one of my tutorials step by step, how you can send [notifications](https://www.youtube.com/watch?v=6RzB4HXzQyA&t=3s&list=PLn2n4GESV0AmXOWOam729bC47v0d0Ohee&index=17) to specific users using Node.js. You can also take a look at my answer from this [post](https://stackoverflow.com/questions/48298993/push-notifications-on-content-change/48299840). – Alex Mamo Oct 04 '21 at 09:30
  • *firebaser here* 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 (including anyone reading this question) 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 Oct 04 '21 at 14:21

0 Answers0