36 lines
1.3 KiB
TypeScript
36 lines
1.3 KiB
TypeScript
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]);
|
||
}
|