Skip to content

Instantly share code, notes, and snippets.

@joelash
Last active December 14, 2021 11:46
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelash/06dcd13dc742382a4749a1d12ff0e9d8 to your computer and use it in GitHub Desktop.
Save joelash/06dcd13dc742382a4749a1d12ff0e9d8 to your computer and use it in GitHub Desktop.
React Native Detect Backgrounding/Foregrounding
import React from 'react';
import {
AppState,
} from 'react-native';
import Expo from 'expo';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
appState: AppState.currentState,
};
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_backgroundState(state) {
return state.match(/inactive|background/);
}
_handleAppStateChange = (nextAppState) => {
if (this._backgroundState(nextAppState)) {
console.log("App is going background");
} else if (this._backgroundState(this.state.appState) && (nextAppState === 'active')) {
console.log("App is coming to foreground");
}
this.setState({appState: nextAppState});
}
}
@NicholusMuwonge
Copy link

Thank you

@Nagasai97
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment