Files
frontend/src/hooks/useRegisterPushDevice.ts

37 lines
1.0 KiB
TypeScript
Raw Normal View History

import { useEffect, useRef } from 'react';
import { Platform } from 'react-native';
import { jpushService } from '../services/notification/jpushService';
import { isAutoStartAllowed } from '../services/consent/autoStartConsent';
export function useRegisterPushDevice(isAuthenticated: boolean, userID?: string) {
const deviceRegistered = useRef(false);
useEffect(() => {
if (Platform.OS === 'web' || !isAuthenticated || !userID) return;
// 仅在用户同意自启动后才初始化 JPush
if (!isAutoStartAllowed()) {
console.log('[useRegisterPushDevice] 用户未同意自启动,跳过 JPush 初始化');
return;
}
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]);
}