两种类型的 FCM 推送通知负载(通知与数据)之间的区别以及它们何时到达 Android FirebaseMessagingService?

nca*_*sas 2 android firebase firebase-cloud-messaging

在 Firebase 推送通知中,有效负载可以是“通知”或“有效负载”类型,但它们是否到达(或不到达)取决于应用程序是否处于后台以及其他详细信息。请澄清它们。

nca*_*sas 12

(本回答主要针对Android设备)

Firebase Cloud Messaging (FCM) push notifications can be of three types : notification, data and notification+data.

  • Notification messages are meant to be received by the Android operating system itself, with no intervention by the app. When received by Android, they will be shown as a notification in the tray. Some details:

    • The tray notification will not be shown if received when your app is in the foreground.
    • You can implement a FirebaseMessagingService (see the data payload for more info on this), which will receive the message if your app is in the foreground. In your FirebaseMessagingService, you can show a tray notification yourself (or do whatever you want) when you receive the message.
    • When sending the message, you can specify what happens when the user clicks on the notification; this can be controlled by either specifying an activity in the click_action Android-specific option (see this) or by specifying an URL in the link property and having your app configure an intent filter associated with the URL you specified.
  • Data messages are meant to be received by an Android service of your app. This service can, in principle (see below [*]), receive the messages when your app is in the foreground, in the background, or not running at all. Some details:

    • To implement the service, you have to extend FirebaseMessagingService and configure it in your app's manifest.
    • When you receive the message in your FirebaseMessagingService, you can decide to emit a local notification to be shown in the tray. You can do this either when your app is in the background or in the foreground, in principle (see below [*]). Of course, you may also decide to do other stuff instead (or apart) of showing the tray notification.
    • [*] 一些手机制造商,尤其是小米和 Oppo 等中国制造商,实施了一些节省电池的机制,其中包括终止服务。这意味着,默认情况下,除非您的应用程序位于前台,否则您的 FirebaseMessagingService 将不会在这些手机上运行,​​因此,当您的应用程序不在前台时,它不会接收您的数据有效负载。除非用户专门将您的应用程序列入白名单,否则无法解决此问题。Whatapp 或 Gmail 等著名应用程序默认包含在白名单中,但您的应用程序不会;因此,如果您依赖数据有效负载并且希望您的应用程序在此类手机上运行,​​您最好引导用户配置他们的手机以允许它;在这里您可以了解如何为小米 (Miui) 设备执行此操作。从Android 9(API 级别 28)开始,具有后台限制的普通 Android 设备中也可能发生这种情况,但行为相反:除非用户请求,否则您的服务不会被终止;您可以使用ActivityManager.isBackgroundRestricted检查这一点
  • 通知+数据消息包括两种类型的有效负载。它们的行为与仅通知有效负载的消息完全相同:

    • 当您的应用程序处于后台时,Android 会在托盘中显示通知。data如果应用程序在用户单击(如上所述)时收到意图调用,则有效负载可供应用程序访问intent.extras
    • 当您的应用程序位于前台时,您的 FirebaseMessagingService 会收到包含数据负载内容的通知。