【问题标题】:Local Schedule Notification react native本地计划通知反应原生
【发布时间】:2019-09-29 06:26:27
【问题描述】:

我是 React Native 的新手,我正在尝试实现一个功能,让应用程序每天在特定的日期和时间向用户发送通知,提醒用户吃药(时间和日期以及数据存储在 mongodb服务器,所以我将使用 axios 来获取它们) 如果应用程序关闭或在后台,通知仍然有效吗? 让它工作容易吗? 有谁知道实现这一目标的方法,有可能吗?

谢谢

【问题讨论】:

  • 你发现了吗?我正在尝试做这样的事情。
  • @RohitKashyap 您找到解决方案了吗?这里的要求相同

标签: react-native push-notification notifications expo


【解决方案1】:

是的!!!这个有可能。您有很多选择,其中包括:

1) 为 iOS 和 Android 中的 HeadlessTask 使用 background-fetch,这是一个不错的库 https://github.com/jamesisaac/react-native-background-task

2) 从服务器推送通知以确保应用程序唤醒应用程序(除非它已被操作系统杀死)。在 iOS 中,请确保调用 notification.finish() 以避免被任务处理程序算法区分。

没有 1 的简单示例如下所示(未测试!!):

import React from 'react'
import { Text } from 'react-native'
import BackgroundTask from 'react-native-background-task'
import { Notifications, Permissions, Constants } from 'expo';

BackgroundTask.define(async () => {

 // if time is 12pm, fire off a request with axios to fetch the pills info
  const response = await fetch('http://pills-server')


    const text = await response.text()

  // Data persisted to AsyncStorage can later be accessed by the foreground app
  await AsyncStorage.setItem('@MyApp:key', text)  

  // Notification configuration object
  const localNotification = {
        title: text,
        body: 'msg',
        data: data,
        ios: {
          sound: true
        }
      }

 // trigger notification, note that on ios if the app is open(in foreground) the notification will not show so you will need to find some ways to handling it which is discribed here https://docs.expo.io/versions/latest/guides/push-notifications

      Notifications
         .presentLocalNotificationAsync(localNotification)
         .catch((err) => {
            console.log(err)
         })


      BackgroundTask.finish()
})

class MyApp extends React.Component {

  async componentDidMount() {
    // allows the app to recieve notifications (permission stuff)
    this.registerForPushNotificationsAsync().then(() => {
      BackgroundTask.schedule()
    });

  }

  registerForPushNotificationsAsync = async () => {

    const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
    if (status !== 'granted') {
      return;
    }
    let deviceToken = await Notifications.getExpoPushTokenAsync()

  }



  render() {
    return <Text>Hello world</Text>
  }
}

对于第二个,想法是服务器应该以某种方式像 cron 作业一样定期根据存储在数据库中的不同时间/日期和药丸信息向所有用户设备发送通知。

注意:对于 expo 的服务器端实现,您可以将 https://github.com/expo/expo-server-sdk-node 用于 node.js 项目,此处列出了其他 sdk:https://docs.expo.io/versions/latest/guides/push-notifications/

import React from 'react'; 
import { Notifications, Permissions, Constants } from 'expo';
import { Text, View } from 'react-native'

class App extends React.Component {

  registerForPushNotificationsAsync = async () => {
    const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
    // prevent device from registering more than once
    if (status !== 'granted') {
     return;
    }

    // get unique token of the device that the server can use to push notification to 
    the device
    let deviceToken = await Notifications.getExpoPushTokenAsync();

    // call a method that sends the device token to the server, in which server stores somewhere and uses in the future
    this.props.registerToken({ deviceToken }).then(() => {

     // the listener here, is called whenever a push notification comes from the server or when the user clicks on the notification at the device tray
      this.notificationSubscription = 
         Notifications.addListener(this.handleNotification);
    })
  }

  handleNotification = (notification) => {

    if (notification.origin === 'selected') {
      // The notification was clicked from the tray by the user i.e selected
      // do stuff to handle selection
    } else {
     // The notification originated from the server
      const localNotification = {
        title: notification.title,
        body: notification.message,
        data: data,
        ios: {
          sound: true
        }
      }
      Notifications.presentLocalNotificationAsync(localNotification).catch((err) => {
        console.log(err)
      })
    }

  }

  async componentDidMount() {

    this.registerForPushNotificationsAsync().then(() => {
    });

  }


  render() {
    return (
     <View>
       <Text>Helllo world</Text>
     </View>
    );
  }
}

请注意,这些解决方案尚未经过测试,可能包含一些错误,但总体思路保持不变,可以进行调整:)。

希望对你有帮助。

【讨论】:

  • 我正在使用 mongoose 作为服务器,这只能通过使用第一种方法(例如从服务器获取日期和时间并生成本地通知)或服务器端步骤(添加 cron 作业)来工作有必要吗?
  • 添加一个cron作业是第二种方法,你只能使用第一种
  • 如果应用程序关闭,我会收到通知吗?或者一旦我打开应用程序并且我试图实现第一种方法但我得到了这个错误(无法获得设备的 GCM 令牌),所有通知都会触发?
  • 您应该在“后台”库的帮助下在应用关闭时收到通知。你在什么时候收到错误?如果您没有使用“expo start”运行应用程序,也不是说您可能会遇到错误
  • 我正在使用 react native expo,所以我总是使用 expo start 运行项目
猜你喜欢
  • 2019-05-16
  • 1970-01-01
  • 2021-02-09
  • 1970-01-01
  • 1970-01-01
  • 2018-01-17
  • 2017-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多