백그라운드 상태에서 진행하고 싶은 작업이 있다.
백그라운드 상태에서 무언가를 하려면 일단 앱의 상태(포그라운드인지, 백그라운드인지)부터 체크해야 한다.
알아보니 리액트 네이티브에서 감지하는 방법과 안드로이드 네이티브에서 감지하는 방법 두가지가 있었다.
일단은 리액트 네이티브에서 감지하는 방법 먼저!
(실습 환경은 React Native CLI이지만, expo에서도 큰 차이가 있을것 같지는 않음)
RN에서는 AppState라는 친절한 API가 제공된다.
AppState can tell you if the app is in the foreground or background, and notify you when the state changes.
AppState is frequently used to determine the intent and proper behavior when handling push notifications.
(AppState는 앱이 포그라운드에 있는지 백그라운드에 있는지 말해주고, 상태가 바뀔때마다 알려줄 수 있습니다. 푸시 알림을 처리할 때 의도된 동작을 하는 데 자주 사용됩니다.)
AppState는 다음과 같은 상태들이 있다.
addEventListener를 사용해 이벤트가 발생할때마다 실행할 콜백을 지정할 수 있다.
다음과 같은 이벤트들이 있다.
이 중 change를 이용해 앱의 상태가 변화될때를 감지할 수 있다.
AppStateStatic.addEventListener(type: AppStateEvent, listener: (state: AppStateStatus) => void): NativeEventSubscription
addEventListener("이벤트 타입", state => 동작) 형태로 사용하면 된다.
앱 상태 감지가 필요한 부분에 넣어주면 된다.
나는 컴포넌트에 상관 없이 가장 상위인 App.tsx에 넣어주었다.
const appState = useRef(AppState.currentState);
AppState.currentState를 이용해 현재 상태를 appState에 담아준다.
AppState.addEventListener('change', nextAppState => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === 'active'
) {
console.log('앱이 포그라운드로 전환됩니다!');
}
appState.current = nextAppState;
console.log('AppState', appState.current);
});
addEventListener로 change를 감지한다.
if블록 안의 내용은 appState(현재 상태, change 전)가 inactive 혹은 background이고(=백그라운드 상태), nextAppState(바뀐 상태, change 후)가 active라면(=포그라운드) 콘솔을 출력하는 내용이다.
그리고 appState를 바뀐 상태로 업데이트 하고, 다시 콘솔을 출력한다.
⬆️홈 화면 등으로 백그라운드 상태 진입시
⬆️다시 앱 화면으로 돌아가 포그라운드 상태 진입시