首页 文章

应用在后台时更新Firebase推送通知

提问于
浏览
1

如何在应用程序处于后台时更新包含数据有效负载的Firebase推送通知?有没有办法在Firebase API的通知中指定通知ID?

我的请求json到firebase api .

{
"registration_ids": ["device id"], 
"collapse_key": "Updates Available"
"notification": {
                    "title": "title", 
                    "desc": "description",
                    "body": "Message received", 
                    "sound": "TYPE_NOTIFICATION",
                    "click_action": "sometargetAction"
                },
"data":         {
                    "user": 
                    {
                        "id": 2
                        "name":"leapingwolf", 
                        "occupation": "passionate coder"
                    }
                }
}

当应用程序在onMessageReceived函数中处于前台时,我使用“user”的id附加到传递的推送通知,如此

User user = remoteMessage.getData().get("user");
        Gson gson = new GsonBuilder().create();
        User userModel =  gson.fromJson(user, User.class);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("FCM Message With Payload")
                .setContentText(messageBody)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(userModel.getId(), notificationBuilder.build());

整个项目在github https://github.com/akshatashan/FirebaseCloudMessagingDemo

2 回答

  • 3

    我根据链接中发布的答案找出了解决方案How to handle notification when app in background in Firebase

    总而言之,如果请求json没有通知标记,则无论应用程序是否在后台,都会调用onMessageReceived . 发送数据标记中的所有相关字段并在onMessageReceived中解析它 .

  • 1

    我想你要找的是Collapsible Messages

    可折叠消息是一条消息,如果尚未传递给设备,则该消息可能被包含相同折叠密钥的新消息替换 .

    对于message types(通知和数据),似乎它们都可以设置为可折叠,在您的情况下,您要求的数据有效负载:

    数据消息客户端应用程序负责处理数据消息 . 数据消息只有自定义键值对 . 使用您的应用服务器和FCM服务器API:仅设置数据密钥 . 可以是可折叠的,也可以是不可折叠的 .

    所以简单地说,你只需要相应地使用collapse_key

    此参数标识可折叠的一组消息(例如,使用collapse_key:“可用更新”),以便在可以恢复传递时仅发送最后一条消息 . 这旨在避免在设备重新联机或变为活动状态时发送过多相同的消息 . 请注意,无法保证发送消息的顺序 . 注意:在任何给定时间最多允许4个不同的折叠键 . 这意味着FCM连接服务器可以同时为每个客户端应用程序存储4个不同的发送到同步消息 . 如果超过此数字,则无法保证FCM连接服务器将保留哪4个折叠键 .

相关问题