Firebase onMessageReceived not called when app in background

前端 未结 26 2700
粉色の甜心
粉色の甜心 2020-11-22 02:32

I\'m working with Firebase and testing sending notifications to my app from my server while the app is in the background. The notification is sent successfully, it even appe

26条回答
  •  攒了一身酷
    2020-11-22 03:07

    If app is in background Fire-base by default handling notification But if we want to our custom notification than we have to change our server side, which is responsible for to send our custom data(data payload)

    Remove notification payload completely from your server request. Send only Data and handle it in onMessageReceived() otherwise your onMessageReceived will not be triggered when app is in background or killed.

    now,your server side code format look like,

    {
      "collapse_key": "CHAT_MESSAGE_CONTACT",
      "data": {
        "loc_key": "CHAT_MESSAGE_CONTACT",
        "loc_args": ["John Doe", "Contact Exchange"],
        "text": "John Doe shared a contact in the group Contact Exchange",
        "custom": {
          "chat_id": 241233,
          "msg_id": 123
        },
        "badge": 1,
        "sound": "sound1.mp3",
        "mute": true
      }
    }
    

    NOTE: see this line in above code
    "text": "John Doe shared a contact in the group Contact Exchange" in Data payload you should use "text" parameter instead of "body" or "message" parameters for message description or whatever you want to use text.

    onMessageReceived()

    @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            Log.e(TAG, "From: " + remoteMessage.getData().toString());
    
            if (remoteMessage == null)
                return;
    
            // Check if message contains a data payload.
            if (remoteMessage.getData().size() > 0) {
               /* Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());*/
                Log.e(TAG, "Data Payload: " + remoteMessage);
    
                try {
    
                    Map params = remoteMessage.getData();
                    JSONObject json = new JSONObject(params);
                    Log.e("JSON_OBJECT", json.toString());
    
    
                    Log.e(TAG, "onMessageReceived: " + json.toString());
    
                    handleDataMessage(json);
                } catch (Exception e) {
                    Log.e(TAG, "Exception: " + e.getMessage());
                }
            }
        }
    

提交回复
热议问题