Issue with FCM notification

2019-06-06 07:06发布

问题:

I am using Firebase for sending push notification to my app and want to save some values to sharedpreferences. Its working perfectly when the app is foreground but it is not saving the values when the app is in background. My code looks like this:

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e("Remotemessage",remoteMessage.toString());

        String Heading = remoteMessage.getNotification().getTitle();
        String message = remoteMessage.getNotification().getBody();
        Map<String, String> data = remoteMessage.getData();
        Log.e("Firebase notification ", " KEY1");
        sessionManager=new SessionManager(this);

        Log.e("Firebase notification ", " KEY"+data.get("click_action"));
        Log.e("Firebase notification ", " KEY new"+data.get("key"));
        int studentid= Integer.parseInt(data.get("student_id"));
        Log.e("STUDENT ID",""+studentid);
        if(studentid!=0)
        {
            sessionManager.saveStudentId(studentid);

        } 
}

but notification is showing both cases. How to solve this issue??

回答1:

Basing from your post, I'll presume that you are sending a payload that contains both notification and data messages. See Message Types for more details.

As can be seen in the Handling Messages for Android documentation, when sending a payload that contains both message type while the the app is in background, the message (notification data) will be handled by the Android System Tray.

There are two things you could do:

  1. Send a data-only message payload, so that onMessageReceived() will be handling the message regardless if your app is in foreground or background.

  2. Implement the handling in getting the details in your data payload after the user taps on the notification in the Android system tray. See my answer here.