Search code examples
javaandroidfirebasefirebase-notifications

Firebase Notifications not being received when app is in background even if data payload is passed


Now I know that if I send data messages, the notifications will come even if the app is in the background. But I am receiving no notifications whatsoever even after sending data messages.

I'm using Postman for testing purposes and here's my body of my Postman Request:

{
 "to" : (device token),

 "data" : {
     "body" : "great match!",
     "title" : "Portugal vs. Denmark",
     "content_available" : true,
     "priority" : "high",
     "sound": "default",
     "time_to_live":"2419200"
  } 
}

And this is my onMessageReceived() funtion:

public void onMessageReceived(RemoteMessage remoteMessage) {

    Map<String,String> data=remoteMessage.getData();
    String title=data.get("title");
    String body=data.get("body");

    if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
        try {
            JSONObject json = new JSONObject(remoteMessage.getData().toString());
            sendPushNotification(title,body);

        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
}

And this is what my sendPushNotification() function looks like:

private void sendPushNotification(String title,String message) {

    try {

        String imageUrl="";
        MyNotificationManager mNotificationManager = new MyNotificationManager(getApplicationContext());
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        if(imageUrl.equals("null")){
            mNotificationManager.showSmallNotification(title, message, intent);
            mNotificationManager.playNotificationSound();
        }else{
            mNotificationManager.showBigNotification(title, message, imageUrl, intent);
            mNotificationManager.playNotificationSound();
        }

    } catch (Exception e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    }
}

I was following this question on stack overflow : How to handle notification when app in background in Firebase

P.S.: When app is in the foreground, notifications are being received just fine.


Solution

  • As you could see on my post, for specific ids you should use "registration_ids": ["{device-token}","{device2-token}","{device3-token}"] key and values instead of ”to”. That’s for topics