当应用未运行时,Firebase将通知保存到数据库不起作用

时间:2016-06-09 06:00:26

标签: android firebase firebase-cloud-messaging

我在我的应用中处理FCM次通知。在

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());
    }

但是当应用未运行或处于后台模式时,我无法保存这些通知。

我正在使用"定期活动"用于处理和显示应用程序中的通知。

this链接

中所述

不知道我错过了什么。

1 个答案:

答案 0 :(得分:2)

当您的应用在后台并且您的通知中包含notification密钥时,Android中的Firebase通知不会发送到您的注册消息服务。要确保您的服务始终处理通知,请不要使用notification字段。 而是使用data字段来实现此目的。

实际上,使用Firebase的notification字段的一个缺点是您无法为系统托盘通知指定大小图标。它只允许您设置一个图标。

但请注意,这不是“通用”解决方案,因为当没有notification字段时,iOS用户将无法在后台收到通知。

话虽如此,我认为现在最好的解决方案是向Android用户发送如下通知:

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

并在您的服务中处理它:

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

对于iOS用户,请使用标准方式:

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

围绕这个主题here

进行了大量讨论