feat: 添加快捷动作功能,支持快速记录饮水量,更新相关配置和服务
This commit is contained in:
76
hooks/useQuickActions.ts
Normal file
76
hooks/useQuickActions.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { useWaterData } from '@/hooks/useWaterData';
|
||||
import { getInitialQuickAction } from '@/services/quickActions';
|
||||
import { Toast } from '@/utils/toast.utils';
|
||||
import * as Haptics from 'expo-haptics';
|
||||
import * as QuickActions from 'expo-quick-actions';
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
|
||||
export const useQuickActions = () => {
|
||||
const { addWaterRecord } = useWaterData();
|
||||
const subscriptionRef = useRef<any>(null);
|
||||
|
||||
// 处理快捷动作
|
||||
const handleQuickAction = useCallback(async (action: any) => {
|
||||
console.log('处理快捷动作:', action);
|
||||
|
||||
// 触发震动反馈
|
||||
if (process.env.EXPO_OS === 'ios') {
|
||||
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
|
||||
}
|
||||
|
||||
// 检查是否是饮水快捷动作
|
||||
if (action.id?.startsWith('drink_water')) {
|
||||
const amount = action.params?.amount || 250; // 默认250ml
|
||||
|
||||
try {
|
||||
// 添加饮水记录
|
||||
const success = await addWaterRecord(amount);
|
||||
if (success) {
|
||||
Toast.success(`已记录饮水 ${amount}ml`);
|
||||
} else {
|
||||
Toast.error('添加饮水记录失败,请稍后重试');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('快捷饮水失败:', error);
|
||||
Toast.error('添加饮水记录失败,请稍后重试');
|
||||
}
|
||||
}
|
||||
}, [addWaterRecord]);
|
||||
|
||||
// 设置快捷动作监听器
|
||||
useEffect(() => {
|
||||
const setupListener = () => {
|
||||
try {
|
||||
// 先处理初始快捷动作(如果应用是通过快捷动作启动的)
|
||||
const initialAction = getInitialQuickAction();
|
||||
if (initialAction) {
|
||||
console.log('检测到初始快捷动作:', initialAction);
|
||||
handleQuickAction(initialAction);
|
||||
}
|
||||
|
||||
// 设置监听器处理后续的快捷动作
|
||||
subscriptionRef.current = QuickActions.addListener(async (action) => {
|
||||
await handleQuickAction(action);
|
||||
});
|
||||
|
||||
console.log('快捷动作监听器已设置');
|
||||
} catch (error) {
|
||||
console.error('设置快捷动作监听器失败:', error);
|
||||
}
|
||||
};
|
||||
|
||||
setupListener();
|
||||
|
||||
// 清理函数
|
||||
return () => {
|
||||
if (subscriptionRef.current) {
|
||||
subscriptionRef.current.remove();
|
||||
console.log('快捷动作监听器已清理');
|
||||
}
|
||||
};
|
||||
}, [handleQuickAction]);
|
||||
|
||||
return {
|
||||
handleQuickAction,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user