📚
ReactNativeでバックグラウンドからの復帰を検知する
ReactNativeでバックグラウンドからの復帰を検知する方法。
ReactNative が提供する AppState
が利用できる。
自分の場合、しばらくバックグラウンドに滞在した後にアプリに戻ってきた場合にある処理をしたかった。
以下のように実装すればOK。
// App.tsx 的なコンポーネント
import { useEffect, useRef } from "react";
import { AppState, AppStateStatus } from "react-native";
const App = () => {
const appState = useRef(AppState.currentState);
const lastActiveTime = useRef(Date.now());
const watchStateChanges = async (nextAppState: AppStateStatus) => {
const previousState = appState.current;
const timeSinceLastActive = Date.now() - lastActiveTime.current;
if (previousState === "background" && nextAppState === "active") {
// 5分
const BACKGROUND_THRESHOLD = 60 * 1000 * 5;
if (timeSinceLastActive > BACKGROUND_THRESHOLD) {
// ここで処理実行
}
}
if (nextAppState === "active") {
lastActiveTime.current = Date.now();
}
appState.current = nextAppState;
}
useEffect(() => {
const subscriber = AppState.addEventListener('change', watchStateChanges);
return () => {
// 解除を忘れない
subscriber.remove()
};
}, [])
}
iOS の場合は active
と background
以外にも inactive
という状態もある。
Discussion