18 KiB
id, title, original_id
| id | title | original_id |
|---|---|---|
| version-0.22-appstate | appstate | appstate |
AppState # | Edit on GitHub |
AppState can tell you if the app is in the foreground or background,
and notify you when the state changes.
AppState is frequently used to determine the intent and proper behavior when handling push notifications.
App States #
active- The app is running in the foregroundbackground- The app is running in the background. The user is either in another app or on the home screeninactive- This is a transition state that currently never happens for typical React Native apps.
For more information, see Apple's documentation
Basic Usage #
To see the current state, you can check AppState.currentState, which
will be kept up-to-date. However, currentState will be null at launch
while AppState retrieves it over the bridge.
This example will only ever appear to say "Current state is: active" because
the app is only visible to the user when in the active state, and the null
state will happen only momentarily.
Methods #
Properties #
currentState: TypeCastExpression #
Examples # | Edit on GitHub |
var React = require('react-native'); var { AppState, Text, View } = React;
var AppStateSubscription = React.createClass({ getInitialState() { return { appState: AppState.currentState, previousAppStates: [], }; }, componentDidMount: function() { AppState.addEventListener('change', this._handleAppStateChange); }, componentWillUnmount: function() { AppState.removeEventListener('change', this._handleAppStateChange); }, _handleAppStateChange: function(appState) { var previousAppStates = this.state.previousAppStates.slice(); previousAppStates.push(this.state.appState); this.setState({ appState, previousAppStates, }); }, render() { if (this.props.showCurrentOnly) { return ( <View> <Text>{this.state.appState}</Text> </View> ); } return ( <View> <Text>{JSON.stringify(this.state.previousAppStates)}</Text> </View> ); } });
exports.title = 'AppState'; exports.description = 'app background status'; exports.examples = [ { title: 'AppState.currentState', description: 'Can be null on app initialization', render() { return <Text>{AppState.currentState}</Text>; } }, { title: 'Subscribed AppState:', description: 'This changes according to the current state, so you can only ever see it rendered as "active"', render(): ReactElement { return <AppStateSubscription showCurrentOnly={true} />; } }, { title: 'Previous states:', render(): ReactElement { return <AppStateSubscription showCurrentOnly={false} />; } }, ];