Files
frontend/src/hooks/useRegisterPushDevice.ts

36 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useRef } from 'react';
import { Platform } from 'react-native';
import { jpushService } from '../services/notification/jpushService';
export function useRegisterPushDevice(isAuthenticated: boolean, userID?: string) {
const deviceRegistered = useRef(false);
useEffect(() => {
if (Platform.OS === 'web' || !isAuthenticated || !userID) return;
// JPush 初始化只取决于登录态——这是基础推送通道(获取 RegistrationID、
// 向服务器注册设备 token与"是否允许后台自启动/保活"无关。
// 后台保活由 backgroundService 控制;退后台是否保持 JPush 长连接由
// jpushService._setBackgroundKeepLongConn() 根据 autoStart 同意状态自行处理。
// 若在此处用 consent 拦截 init未同意用户将永远拿不到 RegistrationID
// 即便在前台/已授予通知权限也无法收到推送。
if (!deviceRegistered.current) {
deviceRegistered.current = true;
jpushService.initialize().then((ok) => {
if (ok && userID) {
jpushService.setAliasForUser(userID);
}
});
}
return () => {
if (!isAuthenticated) {
deviceRegistered.current = false;
jpushService.cleanup();
}
};
}, [isAuthenticated, userID]);
}