/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ 'use strict'; import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import RNTesterText from '../../components/RNTesterText'; import React from 'react'; import {useEffect, useState} from 'react'; import {AppState, Platform} from 'react-native'; type Props = { detectEvents?: boolean, showCurrentOnly?: boolean, showMemoryWarnings?: boolean, }; function AppStateSubscription(props: Props) { const [currentAppState, setCurrentAppState] = useState( AppState.currentState, ); const [previousAppStates, setPreviousAppStates] = useState([]); const [memoryWarnings, setMemoryWarnings] = useState(0); const [eventsDetected, setEventsDetected] = useState([]); useEffect(() => { const subscriptions = [ AppState.addEventListener('change', handleAppStateChange), AppState.addEventListener('memoryWarning', handleMemoryWarning), ]; if (Platform.OS === 'android') { subscriptions.push( AppState.addEventListener('focus', handleFocus), AppState.addEventListener('blur', handleBlur), ); } return () => { subscriptions.forEach(subscription => subscription.remove()); }; }, []); const handleMemoryWarning = () => { setMemoryWarnings(prev => prev + 1); }; const handleBlur = () => { setEventsDetected(prev => [...prev, 'blur']); }; const handleFocus = () => { setEventsDetected(prev => [...prev, 'focus']); }; const handleAppStateChange = (appState: string) => { setPreviousAppStates(prev => [...prev, appState]); setCurrentAppState(appState); }; if (props.showMemoryWarnings) { return {memoryWarnings}; } if (props.showCurrentOnly) { return ( {currentAppState} ); } if (props.detectEvents) { return {JSON.stringify(eventsDetected)}; } return ( {previousAppStates.join(', ')} ); } exports.title = 'AppState'; exports.category = 'Basic'; exports.documentationURL = 'https://reactnative.dev/docs/appstate'; exports.description = 'app background status'; exports.examples = [ { title: 'AppState.currentState', description: 'Can be null on app initialization', render(): React.Node { return ( {AppState.currentState} ); }, }, { title: 'Subscribed AppState:', description: 'This changes according to the current state, so you can only ever see it rendered as "active"', render(): React.MixedElement { return ; }, }, { title: 'Previous states:', render(): React.MixedElement { return ; }, }, { platform: 'ios', title: 'Memory Warnings', description: 'In the IOS simulator, hit Shift+Command+M to simulate a memory warning.', render(): React.MixedElement { return ; }, }, { platform: 'android', title: 'Focus/Blur Events', description: 'In the Android simulator, toggle the notification drawer to fire events.', render(): React.MixedElement { return ; }, }, ] as Array;