1import NativeUtils from '@/native/utils'; 2import StateMapper from '@/utils/stateMapper'; 3import {useEffect, useRef, useState} from 'react'; 4import BackgroundTimer from 'react-native-background-timer'; 5// import TrackPlayer from "react-native-track-player"; 6 7let deadline: number | null = null; 8const stateMapper = new StateMapper(() => deadline); 9// let closeAfterPlayEnd = false; 10// const closeAfterPlayEndStateMapper = new StateMapper(() => closeAfterPlayEnd); 11let timerId: any; 12 13function setTimingClose(_deadline: number | null) { 14 deadline = _deadline; 15 stateMapper.notify(); 16 timerId && BackgroundTimer.clearTimeout(timerId); 17 if (_deadline) { 18 timerId = BackgroundTimer.setTimeout(() => { 19 // todo: 播完整首歌再关闭 20 NativeUtils.exitApp(); 21 // if(closeAfterPlayEnd) { 22 // TrackPlayer.addEventListener() 23 // } else { 24 // // 立即关闭 25 // NativeUtils.exitApp(); 26 // } 27 }, _deadline - Date.now()); 28 } else { 29 timerId = null; 30 } 31} 32 33function useTimingClose() { 34 const _deadline = stateMapper.useMappedState(); 35 const [countDown, setCountDown] = useState( 36 deadline ? deadline - Date.now() : null, 37 ); 38 const intervalRef = useRef<any>(); 39 40 useEffect(() => { 41 // deadline改变时,更新定时器 42 // 清除原有的定时器 43 intervalRef.current && clearInterval(intervalRef.current); 44 intervalRef.current = null; 45 46 // 清空定时 47 if (!_deadline || _deadline <= Date.now()) { 48 setCountDown(null); 49 return; 50 } else { 51 // 更新倒计时 52 setCountDown(Math.max(_deadline - Date.now(), 0) / 1000); 53 intervalRef.current = setInterval(() => { 54 setCountDown(Math.max(_deadline - Date.now(), 0) / 1000); 55 }, 1000); 56 } 57 }, [_deadline]); 58 59 return countDown; 60} 61 62export {setTimingClose, useTimingClose}; 63