안드로이드에서 video가 재생되는 상태에서 video 스크린이 아닌 comment 나 더보기 스크린으로 이동 후 잠금버튼이나 홈버튼을 눌렀을 시 background play가 일시정지 되지 않는 이슈가 있었습니다.
AppState는 앱이 동작하거나 백그라운드에 있을 때, 상태가 변경 되는것을 알려줍니다.
AppState를 이용하면 앱이 background였다가 foreground 상태로 왔는지, 그 반대인지를 알 수 있습니다.
🔗 참고 링크 : AppState · React Native
AppState.currentState
를 통해서 앱 상태를 알 수 있습니다.
import React, { useRef, useState, useEffect } from "react";
import { AppState, StyleSheet, Text, View } from "react-native";
const AppStateExample = () => {
const appState = useRef(AppState.currentState);
const [appStateVisible, setAppStateVisible] = useState(appState.current);
useEffect(() => {
const subscription = AppState.addEventListener("change", nextAppState => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === "active"
) {
console.log("App has come to the foreground!");
}
appState.current = nextAppState;
setAppStateVisible(appState.current);
console.log("AppState", appState.current);
});
return () => {
subscription.remove();
};
}, []);
return (
<View style={styles.container}>
<Text>Current state is: {appStateVisible}</Text>
</View>
);
};
const VideoItem = () => {
const [curPaused, setCurPaused] = useState(videoProps.paused); // 제스처 정지/재생
const handleAppStateChange = (state) => {
if (state === 'background') {
setCurPaused(true);
} else {
setCurPaused(videoProps.paused);
}
};
}
1️⃣ react-native의 AppState를 import 합니다.
2️⃣ AppState의 값을 받아옵니다.
3️⃣ if문을 통해 AppState가 background 라고 감지하면 pause해주는 handleAppStateChange
함수를 생성합니다.
const VideoItem = () => {
const [curPaused, setCurPaused] = useState(videoProps.paused); // 제스처 정지/재생
useEffect(() => {
// 사용자가 앱의 상태가 변경 되었을 경우 실행
const appStateListener = AppState.addEventListener('change', handleAppStateChange);
return () => {
appStateListener?.remove();
};
}, []);
const handleAppStateChange = (state) => {
if (state === 'background') {
setCurPaused(true);
} else {
setCurPaused(videoProps.paused);
}
};
}
4️⃣ useEffect상에서 AppState 상태 변경에 대한 listener 등록합니다.
성능 개선을 위해 useEffect 내에 listener를 정리하는 remove 메서드를 사용한 return문을 포함