1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import React, {Component} from 'react'; import {AppState, StyleSheet, Text, View} from 'react-native'; class App extends Component { state = { appState: AppState.currentState, }; componentDidMount() { AppState.addEventListener('change', this._handleAppStateChange); } componentWillUnmount() { AppState.removeEventListener('change', this._handleAppStateChange); } _handleAppStateChange = (nextAppState) => { if ( this.state.appState.match(/inactive|background/) && nextAppState === 'active' ) { console.log('App has come to the foreground!'); } this.setState({appState: nextAppState}); console.log(nextAppState); }; render() { return ( <View style={styles.container}> <Text>Current state is: {this.state.appState}</Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, }); export default App; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import React, {useRef, useState, useEffect} from 'react'; import {AppState, StyleSheet, Text, View} from 'react-native'; const App = () => { const appState = useRef(AppState.currentState); const [appStateVisible, setAppStateVisible] = useState(appState.current); useEffect(() => { AppState.addEventListener('change', _handleAppStateChange); return () => { AppState.removeEventListener('change', _handleAppStateChange); }; }, []); const _handleAppStateChange = (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 ( <View style={styles.container}> <Text>Current state is: {appStateVisible}</Text> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, }); export default App; |