import { AppState, AppStateStatus } from 'react-native';
...
const [backgroundTime, setBackgroundTime] = useState<number>(0);
const [foregroundTime, setForegroundTime] = useState<number>(0);
const handleAppStateChange = (nextAppState: AppStateStatus) => {
if (appState.current.match(/inactive|background/) && nextAppState === 'active') {
console.log('foreground 전환');
setForegroundTime(Date.now());
} else {
console.log('background 전환');
setBackgroundTime(Date.now());
}
appState.current = nextAppState;
};
useEffect(() => {
const appStateListener = AppState.addEventListener('change', handleAppStateChange);
return () => {
appStateListener.remove();
};
}, []);
...
setBackgroundTime
으로 background
로 전환되는 시간을 체크하고, setForegroundTime
으로 foreground
로 전환되는 시간을 체크해 두 시간의 차이를 이용한 기능을 구현.