使用 Expo React Native 收听 FCM 推送通知传送 (android)

Listen to FCM push notification delivery with Expo react native (android)

我遇到的问题与this one极为相似。

为了完整起见,我在上面提到了一些小问题,但我现在面临的主要问题是我的应用程序只是不会注意到通知到达。侦听器不会触发。

我尝试了 Legacy Notifications Module and the New Notifications Module:

// Attempt using Legacy Notifications
// https://docs.expo.io/versions/v38.0.0/sdk/legacy-notifications/
import { Notifications as LegacyNotificationsModule } from 'expo';

// Attempt using New Notifications Module
// https://docs.expo.io/versions/v38.0.0/sdk/notifications/
import * as NewNotificationsModule from 'expo-notifications';

LegacyNotificationsModule.addListener(() => {
    // Make any UI change just for we to see it happening
});

NewNotificationsModule.addNotificationReceivedListener(() => {
    // Make any UI change just for we to see it happening
});

// I also tried commenting and uncommenting the code below
NewNotificationsModule.setNotificationHandler({
    handleNotification: async () => ({
        shouldShowAlert: true,
        shouldPlaySound: false,
        shouldSetBadge: false,
    }),
});

回想一下,就像在 the similar issue I linked above 中一样,我 没有 使用 Expo 通知令牌(形式为 ExponentPushToken[xxxxxx])。我正在使用通过 Notifications.getDevicePushTokenAsync().

获得的标准 FCM 令牌

我怎样才能完成这项工作?

我终于想通了。

我已发送 PR to Expo 来改进这方面的文档。

简而言之,引用 my comment on GitHub:

For the app to properly react to the notification, it must come with an extra special field called experienceId. I couldn't find a way to send this field through Firebase Console interface for sending test messages; instead I made it work performing a HTTP POST call with:

  • Headers:
    • Authorization: key=${FIREBASE_SERVER_KEY_TOKEN} (obtained in my Firebase project Settings > Cloud Messaging)
    • Content-Type: application/json
  • Body:
    {
        "to": "<DEVICE_PUSH_NOTIFICATION_TOKEN>",
        "priority": "normal",
        "data": {
            "experienceId": "@anonymous/my-project-slug",
            "title": "Hello",
            "message": "World"
        }
    }
    

一个没有记录的关键信息是,对于像我这样没有 expo 帐户(并且正在独立于 expo 构建所有内容)的人来说,体验 ID 应该以 @anonymous 开头。 Full credits for @awinograd in GitHub for figuring this out.