AppStateIOS
可以告訴你應(yīng)用程序是在前臺還是在后臺,而且狀態(tài)更新時會通知你。 在處理推送通知時,AppStateIOS 經(jīng)常被用于判斷目標(biāo)和適當(dāng)?shù)男袨椤?/p>
Active - 應(yīng)用程序在前臺運行
Background - 應(yīng)用程序在后臺運行。用戶正在使用另一個應(yīng)用程序或者在主屏幕上。
Inactive - 這是一種過渡狀態(tài),目前不會在React Native的應(yīng)用程序上發(fā)生。
想要獲取更多的信息,見 Apple's documentation
為了查看當(dāng)前的狀態(tài),你可以檢查 AppStateIOS.currentState
,該方法會一直保持最新狀態(tài)。然而,當(dāng) AppStateIOS
在橋接器上檢索currentState
時,在啟動時它將會為空。
getInitialState: function() { return { currentAppState: AppStateIOS.currentState, }; }, componentDidMount: function() { AppStateIOS.addEventListener('change', this._handleAppStateChange); }, componentWillUnmount: function() { AppStateIOS.removeEventListener('change', this._handleAppStateChange); }, _handleAppStateChange: function(currentAppState) { this.setState({ currentAppState, }); }, render: function() { return ( <Text>Current state is: {this.state.currentAppState}</Text> ); },
這個例子似乎只能說"當(dāng)前狀態(tài)是:活躍的"因為在 active
狀態(tài)時,應(yīng)用程序只對用戶是可見的,空狀態(tài)只能是暫時的。
static addEventListener(type: string, handler: Function)
通過監(jiān)聽 change
事件類型和提供處理程序,為應(yīng)用程序狀態(tài)變化添加一個處理程序。
static removeEventListener(type: string, handler: Function)
通過傳遞 change
事件類型和處理程序,刪除一個處理程序。
'use strict'; var React = require('react-native'); var { AppStateIOS, Text, View } = React; var AppStateSubscription = React.createClass({ getInitialState() { return { appState: AppStateIOS.currentState, previousAppStates: [], }; }, componentDidMount: function() { AppStateIOS.addEventListener('change', this._handleAppStateChange); }, componentWillUnmount: function() { AppStateIOS.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 = 'AppStateIOS'; exports.description = 'iOS app background status'; exports.examples = [ { title: 'AppStateIOS.currentState', description: 'Can be null on app initialization', render() { return <Text>{AppStateIOS.currentState}</Text>; } }, { title: 'Subscribed AppStateIOS:', 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} />; } }, ];
更多建議: