如何使用云函数在 FCM 中正确指定 channel_id

10 浏览
0 Comments

如何使用云函数在 FCM 中正确指定 channel_id

很遗憾,目前还没有答案。我正在尝试使用Postman进行测试,希望能更快地进行测试。\n我成功通过我的应用程序发送了一条通知,但是通知总是以无声、无振动和无通知图标的方式出现在我的手机的静默通知中,只有在向下滑动时才会在抽屉中出现一条通知。\n为了修复/改善这种情况,我尝试了以下操作:\n

    \n

  1. 使用flutter_local_notifications包创建了一个id为high_importance_channel的Android通知渠道。成功创建了该渠道,因为请求现有渠道的概述时,新创建的渠道显示在其中(其他渠道之间)。新渠道具有importance: 5enableVibration: trueplaySound: true,这样应该可以解决问题。\n
  2. \n

  3. 通过云函数发送一条FCM,使用以下代码:\n
    const functions = require("firebase-functions");
    const admin = require("firebase-admin");
    admin.initializeApp();
    exports.chatNotification = functions.firestore
        .document('chats/{groupId}/chat/{chatId}')
        .onCreate( async (snapshot, context) => {
        const message = {
           "notification": {
               "title": "Message Received",
               "body": "Text Message from " + fromUserName,
             },
           "tokens": registrationTokens,
           "android": {
                 "notification": {
                     "channel_id": "high_importance_channel",
                   },
               },
         };
         admin.messaging().sendMulticast(message)
           .then((response) => {
             console.log(response.successCount + ' messages were sent successfully');
           });
           }
    

    \n

  4. \n

\n但是到目前为止,通知仍然以静默通知的形式出现。我做错了什么?

0
0 Comments

问题出现的原因是在使用FCM进行推送通知时,channel_id参数的指定不正确。这可能导致通知无法正确发送到指定的通道。

解决方法是在payload中正确指定channel_id参数。有两种方式可以实现。

第一种方式是在notification字段中添加android_channel_id参数,如下所示:

var payload = {
  notification: {
    android_channel_id: 'AppChannel',
    title: 'Push Notification Arrived!',
    body: 'Using Cloud Functions',
    sound: 'default',
  },
  data: {
    route: '/someRoute',
  },
};

第二种方式是在android字段中添加notification字段,并在其中指定channelId参数,如下所示:

const message = {
  notification: {
    title: 'Push Notification Arrived!',
    body: 'Using Cloud Functions',
  },
  data: {
    route: '/someRoute',
  },
  android: {
    notification: {
      channelId: "AppChannel",
      priority: 'max',
      defaultSound: 'true',
    },
  },
  token: deviceTokens,
};

另外,需要注意的是,在Android中不支持'importance: 5'参数。可以参考stackoverflow.com/a/70835014/9424323中的解决方法。

通过以上的两种方式,可以正确指定channel_id参数,并确保推送通知能够正确发送到指定的通道。

0