如何在Notifee和FCM中接收后台通知

3
我一直在尝试使用 rnfirebase 在 React Native 中实现使用 FCM 进行通知,同时使用 notifee 处理本地通知。我已经能够通过 Firebase Cloud Messaging 接收到后台通知(即应用被杀死或最小化的状态),并可以使用 notifee 获取前台通知。我现在希望使用 notifee 处理后台通知以保持通知的一致性。以下是代码:
const displayNotification = async () => {
    const channelId = await notifee.createChannel({
      id: 'important',
      name: 'Important Notifications',
      importance: AndroidImportance.HIGH,
    });
    notifee.displayNotification({
      body: 'This message was sent via FCM!',
      android: {
        channelId: channelId,
        actions: [
          {
            title: 'Mark as Read',
            pressAction: {
              id: 'read',
            },
          },
        ],
      },
    });
  };

   messaging().setBackgroundMessageHandler(async remoteMessage => {
      console.log('Message handled in the background!', remoteMessage);
      displayNotification();
    });

    messaging().onMessage(async remoteMessage => {
      console.log('Message handled in the foregourp!', remoteMessage);
      displayNotification();
    });

使用此代码可以获取前台通知。当应用程序最小化时,会收到来自notifee和FCM的两个通知。当应用程序被杀死时,只会收到FCM通知而不是notifee通知。
问题:
1. 如何在应用程序被杀死的状态下从notifee获取通知? 2. 如何禁用FCM后台通知?我需要只从Firebase发送数据通知吗? 3. 在One Plus设备上,由于显示应用程序未运行,因此无法在被杀死的状态下获取FCM通知。我需要在Android清单文件中添加什么?
解决方案:
Q1通过将setBackgroundHandler从useEffect内部移动到hook外部来解决。
Q2尚未解决。
Q3尚未解决。
3个回答

2

backgroundMessageHandler会根据来自FCM的信息创建通知,而触发你自己的通知只会导致两个通知。因此,在backgroundMessageHandler中应删除displayNotification();。此外,backgroundMessageHandler应该位于index.js文件中,而不是你的应用程序中。


1
把它移到外面确实解决了问题,但是为了避免双重通知,我想禁用 FCM 通知。想知道是否有相应的函数可以实现,或者我需要在后端发送没有通知的消息。 同时,如果有什么方法可以让应用在后台运行而不会在最近使用中被强制停止,也请告知。 - ShIvam Rawat
1
很遗憾,backgroundMessageHandler 没有一个简单的参数可以传递来自动停止创建推送通知。如果您不想创建推送通知,请不要从后端发送通知参数,而是只发送包含通知信息的数据,并使用 notifee 从数据构建自己的通知。请确保放置重要属性,否则您的数据将被自动忽略。 - Maximilian Dietel

1

如果您想忽略 FCM 后台通知,只需忽略通知参数。仅发送数据参数,但仅包含数据的消息会在 Android 和 iOS 上以低优先级发送,并且默认情况下不会触发 setBackgroundMessageHandler。要启用此功能,您必须在 Android 上将“优先级”设置为高,并在消息有效负载中为 iOS 启用 content-available 标志。

{
  "to": "User_Device_Token",
  "data": {
     "body": "Body of Your Notification",
     "title": "Title of Your Notification"
  },
  "priority": "high",
  "contentAvailable": true
}

这是从后端传来的有效载荷吗? - Hamed

0
回答问题2。您需要从后端自定义消息对象。
对于NodeJS,
import { getMessaging } from "firebase-admin/messaging";

const message = {
    data: {
      title: "Title",
      body: "This is the body",
    },
    token:
      "fcm-token-here",
  };

  getMessaging()
    .send(message)
    .then((response) => {
      res.json({
        msg: "Sent successfully",
      });
      console.log(response);
    })
    .catch((err) => console.log(err));

如果在消息对象中有通知对象,它将显示Firebase通知。如果你将它改为数据,它将不会显示。你可以从notifee处理数据对象。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接