Firebase Save Notification to DB not working when

2019-07-18 18:48发布

I am handling FCM notifications in my app. in like

public void onMessageReceived(RemoteMessage remoteMessage) {

        Notification notification = new Notification();
        notification.setTitle(remoteMessage.getNotification().getTitle());
        notification.setDescription(remoteMessage.getNotification().getBody());
        DateFormat simpledateFormat = new SimpleDateFormat("dd/MM/yyyy");
        DateFormat simpleTimeFormat = new SimpleDateFormat("hh:mm");
        Date date = new Date(remoteMessage.getSentTime());

        notification.setTime(simpleTimeFormat.format(date));
        Date date2 = new Date();
        notification.setDate(simpledateFormat.format(date2));
        DatabaseHelper databaseHelper = new    DatabaseHelper(getApplicationContext());
        databaseHelper.saveNotification(notification);

        //Calling method to generate notification
        sendNotification(remoteMessage.getNotification().getBody());
    }

but when app is not running or in background mode i am not able to save those notifications.

i am using "Regular activity" for processing and display of notifications in app.

as said in this link

don't know what i am missing.

1条回答
时光不老,我们不散
2楼-- · 2019-07-18 19:07

Firebase notifications in Android are not sent to your registered messages service when your app is in background and your notification contains a notification key. To ensure your service always handles notifications, don't use the notification field. Instead use the data field for that purpose.

Actually one downside of using Firebase's notification field is that you cannot specify a large and small icons for the system tray notification. It only lets you set one icon.

Note however that this is not a "universal" solution since iOS users will not receive a notification in background when there's no notification field present.

Having said that, I think the best solution right now is to send you Android users a notification like the following:

{
    "to":"tHt4D...",
    "data":
    {
        "title":"Nice title",
        "body":"Nice body"
    }
}

and handle it in your service like this:

public void onMessageReceived(RemoteMessage remoteMessage) {
    Map<String, String> data = remoteMessage.getData();
    makeMyCustomNotification(data.get("title"), data.get("body"));
}

For iOS users use the standard way:

{
    "to":"tHt4D...",
    "notification":
    {
        "title":"Nice title",
        "body":"Nice body"
    }
}

There's a big discussion around this topic here

查看更多
登录 后发表回答