ReactNative - background, foreground 전환할 때 타이머 계속 동작하게 구현

이호현·2022년 8월 22일
0

ReactNative

목록 보기
4/5

background, foreground 전환할 때 타이머 계속 동작하게 구현

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로 전환되는 시간을 체크해 두 시간의 차이를 이용한 기능을 구현.

profile
평생 개발자로 살고싶습니다

0개의 댓글