【问题标题】:Remove notification after a certain time in React Native (@react-native-firebase/messaging)在 React Native 中一段时间​​后删除通知 (@react-native-firebase/messaging)
【发布时间】:2021-03-12 21:43:07
【问题描述】:

我有使用 @react-native-firebase/messaging 在 React Native 中工作的推送通知。我在后端使用 FCM,它目前在 iOS 和 Android 上显示操作系统锁屏通知。

我想在一段时间后或经过一段时间后清除给定的通知。有没有办法做到这一点?现在,当我发送通知时,如果我不点击它,它会持续几天。我想在一个小时后或下午 4 点或其他任何时间后取消通知。欢迎使用前端和/或后端解决方案。

我曾假设“ttl”(生存时间)参数会这样做,但事实并非如此。

【问题讨论】:

    标签: firebase react-native react-native-firebase


    【解决方案1】:

    你可以使用像react-native-background-fetch这样的后台处理程序

    在您的 onMessage 或 backgroundMessage 中,使用 scheduleTask() 为您希望的时间安排一个 backgroundTask。

    您可以使用react-native-push-notification 来显示通知,它有一个方法cancelLocalNotifications() 来取消通知 在任务中,您可以根据 id 清除通知

    PushNotification.configure({
      onNotification: (notification) => {
        var {id} = remoteMessage.data
        
        BackgroundFetch.configure({
          minimumFetchInterval: 15
        }, async (taskId) => {
        
          PushNotification().cancelLocalNotifications(id)
          BackgroundFetch.finish(taskId);
        })
        
        BackgroundFetch.scheduleTask({
          taskId: id,
          forceAlarmManager: true,
          delay: 5000 
        });
    
      }
    })
    

    【讨论】:

    • 谢谢,但据我所知,@react-native-firebase/messaging 没有 .cancelDisplayedNotification() 。您的答案是否取决于像 Marcel 的答案那样切换消息接收器?
    • 是的,我没有看到解决方案在消息传递中是不可能的。另一种解决方案是使用 react-native-push-notification。我更新了我的答案
    【解决方案2】:

    TTL 参数仅指定将通知传递给用户设备。例如。手机离线 2 小时后仍然发送消息。

    我不确定是否有使用默认 firebase 包的方法,但 more advanced version of it 似乎能够处理该用例:

    https://notifee.app/react-native/reference/canceldisplayednotification

    我认为您应该能够在后台任务中调用该方法(例如,在收到另一个(静默)通知之后)。

    很遗憾,我还不能自己测试。

    【讨论】:

      【解决方案3】:

      在 iOS 上,您可以使用 badge 设置。如果将其设置为 0,它将删除所有通知。对于您的情况,您可以安排一个“清理”任务,在一定时间后触发以下请求。

      {
        message: {
          notification: {
            body: "" // has to be empty
          },
          android: {
            notification: {
              channel_id: 'some_channel'
            }
          },
          apns: {
            payload: {
              aps: {
                category: 'some_category',
                badge: 0
              }
            }
          },
          token: device_token
        }
      }
      
      

      很遗憾,我还没有找到类似的安卓解决方案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 2021-09-06
        • 1970-01-01
        • 1970-01-01
        • 2019-02-22
        • 2021-01-19
        • 1970-01-01
        相关资源
        最近更新 更多