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