【问题标题】:how to send random local notification message in react-native?如何在 react-native 中发送随机本地通知消息?
【发布时间】:2020-05-04 16:37:53
【问题描述】:

我有一个应用程序需要每天向用户发送带有随机消息的通知,具体取决于他们想要多少通知(每天最多 5 个通知)以及他们想要的时间间隔(例如,通知只会在每天早上 6:00 - 早上 9:00)。

为了详细说明,我正在构建一个功能,其想法是发送我从硬编码数组变量或 json 文件中提取的随机鼓舞人心的消息。

目前我正在使用这个包:https://github.com/zo0r/react-native-push-notification 来创建本地通知。

我尝试设置一个函数,该函数为 localNotificationSchedule 的消息参数返回一个字符串,但是当我这样做时,它没有显示通知,而不是使用常规字符串。

PushNotification.localNotificationSchedule({
  id          : '1',
  userInfo    : { id: userId },
  message     : () => {
    return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5); //trying to return random string every time notification fires.
  },
  date        : moment(Date.now()).add(2, 'seconds').toDate(),
  repeatType  : 'day',
});

我考虑使用其他方法,例如 react-native headless JS,但它仅适用于 android。

也考虑使用https://www.npmjs.com/package/react-native-background-fetch。但是我有一个复杂的通知间隔。例如,用户可以将通知设置为每天早上 6:00 - 6:30 运行,并设置为触发 5 个通知。在此间隔内,通知将每 6 分钟运行一次。

但是 react-native-background-fetch 的最小间隔只有 15 分钟。

我知道这可以通过使用推送通知来完成,但是这样,用户将需要连接才能接收通知,这对于这种情况并不理想。

我从 Ios 应用程序中看到了这一点,所以我知道这是可以实现的。

【问题讨论】:

  • 通知是系统设置还是用户选择?
  • 由用户选择

标签: react-native notifications react-native-push-notification


【解决方案1】:

根据开发人员,您可以尝试多次调用PushNotification.localNotificationSchedule

我所做的是这样的:

const messages = [{text:'',time:0}...];

    messages.map(message=>{
    PushNotification.localNotificationSchedule({
    //... You can use all the options from localNotifications
                    channelId: "my-channel",
                    message: message.text, // (required)
                    date: new Date(Date.now() + (60 + message.time) * 1000), // in 60 secs
                    
                });
    
    })

显示消息数组中的消息,间隔 5 秒。

【讨论】:

    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 1970-01-01
    相关资源
    最近更新 更多