feat: 新增喝水提醒功能,支持定期提醒和目标检查
This commit is contained in:
@@ -81,6 +81,78 @@ export const createNotificationCheckTask = (): BackgroundTask => ({
|
||||
},
|
||||
});
|
||||
|
||||
// 喝水提醒检查任务
|
||||
export const createWaterReminderTask = (): BackgroundTask => ({
|
||||
id: 'water-reminder-task',
|
||||
name: '喝水提醒检查任务',
|
||||
handler: async (data?: any) => {
|
||||
console.log('开始执行喝水提醒检查任务');
|
||||
|
||||
try {
|
||||
// 导入必要的模块
|
||||
const { WaterNotificationHelpers } = await import('@/utils/notificationHelpers');
|
||||
const { getTodayWaterStats } = await import('@/services/waterRecords');
|
||||
const AsyncStorage = (await import('@react-native-async-storage/async-storage')).default;
|
||||
|
||||
// 获取用户信息
|
||||
const userProfileJson = await AsyncStorage.getItem('@user_profile');
|
||||
const userProfile = userProfileJson ? JSON.parse(userProfileJson) : null;
|
||||
const userName = userProfile?.name || '朋友';
|
||||
|
||||
// 检查时间限制:早上9点以前和晚上9点以后不通知
|
||||
const currentHour = new Date().getHours();
|
||||
if (currentHour < 9 || currentHour >= 21) {
|
||||
console.log(`当前时间${currentHour}点,不在通知时间范围内(9:00-21:00),跳过喝水提醒检查`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取今日喝水统计数据
|
||||
let todayStats;
|
||||
try {
|
||||
todayStats = await getTodayWaterStats();
|
||||
} catch (error) {
|
||||
console.log('获取喝水统计数据失败,可能用户未登录或无网络连接:', error);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!todayStats || !todayStats.dailyGoal || todayStats.dailyGoal <= 0) {
|
||||
console.log('没有设置喝水目标或目标无效,跳过喝水检查');
|
||||
return;
|
||||
}
|
||||
|
||||
// 构造今日统计数据
|
||||
const waterStatsForCheck = {
|
||||
totalAmount: todayStats.totalAmount || 0,
|
||||
dailyGoal: todayStats.dailyGoal,
|
||||
completionRate: todayStats.completionRate || 0
|
||||
};
|
||||
|
||||
// 调用喝水通知检查函数
|
||||
const notificationSent = await WaterNotificationHelpers.checkWaterGoalAndNotify(
|
||||
userName,
|
||||
waterStatsForCheck,
|
||||
currentHour
|
||||
);
|
||||
|
||||
if (notificationSent) {
|
||||
console.log('喝水提醒通知已发送');
|
||||
} else {
|
||||
console.log('无需发送喝水提醒通知');
|
||||
}
|
||||
|
||||
console.log('喝水提醒检查任务执行完成');
|
||||
} catch (error) {
|
||||
console.error('喝水提醒检查任务执行失败:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
options: {
|
||||
minimumInterval: 60, // 60分钟最小间隔
|
||||
stopOnTerminate: false,
|
||||
startOnBoot: true,
|
||||
},
|
||||
});
|
||||
|
||||
// 示例任务:缓存清理任务
|
||||
export const createCacheCleanupTask = (): BackgroundTask => ({
|
||||
id: 'cache-cleanup-task',
|
||||
@@ -142,6 +214,7 @@ export const registerDefaultTasks = async (): Promise<void> => {
|
||||
createDataSyncTask(),
|
||||
createHealthDataUpdateTask(),
|
||||
createNotificationCheckTask(),
|
||||
createWaterReminderTask(),
|
||||
createCacheCleanupTask(),
|
||||
createUserAnalyticsTask(),
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user