我正在制作一个日历应用程序,与博览会进行原生反应。我正在考虑使用
Notifications.scheduleNotification
在日历中的事件时间到来时弹出通知。
当用户重置手机时,至少在Android中,通知仍然存在,并且无论如何他们都会收到之前安排的通知。这使我无需添加
BackgroundFetch
来重新安排可能丢失的通知。相反,我在创建活动时安排它们。
但我想:重新安装怎么样?重新安装时我会丢失预定的通知吗?
android中的情况如何?在 iOS 中?
计划的通知存储在应用程序的数据中,卸载应用程序时,其所有数据都会被删除。
您可以结合使用本地存储和后台获取。安装或启动应用程序后,您可以检查本地存储中是否有任何先前安排的通知。如果有的话,您可以使用Notifications.scheduleNotification重新安排它们。
import * as Notifications from 'expo-notifications';
import AsyncStorage from '@react-native-async-storage/async-storage';
async function loadScheduledNotifications() {
const storedNotifications = await AsyncStorage.getItem('scheduledNotifications');
if (storedNotifications) {
const notifications = JSON.parse(storedNotifications);
notifications.forEach(notification => {
Notifications.scheduleNotification(notification);
});
}
}
async function saveScheduledNotification(notification) {
const storedNotifications = await AsyncStorage.getItem('scheduledNotifications');
let notifications = [];
if (storedNotifications) {
notifications = JSON.parse(storedNotifications);
}
notifications.push(notification);
await AsyncStorage.setItem('scheduledNotifications', JSON.stringify(notifications));
}
// Usage
Notifications.scheduleNotification(notification);
saveScheduledNotification(notification);
我们使用 AsyncStorage 来存储和检索计划的通知。当安排通知时,我们将其保存到 AsyncStorage。当应用程序启动时,我们会加载所有先前安排的通知并重新安排它们。