memowake-front/components/message-push.tsx

76 lines
2.6 KiB
TypeScript

import * as Notifications from 'expo-notifications';
import { useRouter } from 'expo-router';
import React, { useEffect, useRef } from 'react';
import { Button, Text, View } from 'react-native';
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false,
shouldShowBanner: true,
shouldShowList: true,
}),
});
export default function MessagePush() {
const router = useRouter();
const notificationListener = useRef<Notifications.Subscription>(null);
const responseListener = useRef<Notifications.Subscription>(null);
useEffect(() => {
// 监听通知点击事件
responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
const data = response.notification.request.content.data;
console.log('通知被点击,数据:', data);
// 根据通知数据跳转到指定页面
if (data.screen === 'ask') {
router.push('/ask');
} else if (data.screen === 'owner') {
router.push('/owner');
}
});
// 清理监听器
return () => {
if (notificationListener.current) {
Notifications.removeNotificationSubscription(notificationListener.current);
}
if (responseListener.current) {
Notifications.removeNotificationSubscription(responseListener.current);
}
};
}, []);
const sendNotification = async () => {
// 请求通知权限
const { status } = await Notifications.requestPermissionsAsync();
if (status !== 'granted') {
alert('请先允许通知权限');
return;
}
// 调度本地通知
await Notifications.scheduleNotificationAsync({
content: {
title: '你有一条新消息 🎉',
body: '点击查看详情内容',
data: { screen: 'ask' },
priority: 'high', // 关键:设置 high 或 max
},
trigger: {
seconds: 2, // 延迟2秒显示
type: Notifications.SchedulableTriggerInputTypes.TIME_INTERVAL // 添加 type 字段
}, // 延迟2秒显示
});
alert('通知将在2秒后显示');
};
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 }}>
<Text></Text>
<Button title="发送通知" onPress={sendNotification} />
</View>
);
}