AppStateIOS 可以告訴你應(yīng)用程序是在前臺(tái)還是在后臺(tái),而且狀態(tài)更新時(shí)會(huì)通知你。
在處理推送通知時(shí),AppStateIOS 經(jīng)常被用于判斷目標(biāo)和適當(dāng)?shù)男袨椤?
為了查看當(dāng)前的狀態(tài),你可以檢查 AppStateIOS.currentState,該方法會(huì)一直保持最新?tīng)顟B(tài)。然而,當(dāng) AppStateIOS 在橋接器上檢索currentState時(shí),在啟動(dòng)時(shí)它將會(huì)為空。
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>
);
},
這個(gè)例子似乎只能說(shuō)"當(dāng)前狀態(tài)是:活躍的"因?yàn)樵?active 狀態(tài)時(shí),應(yīng)用程序只對(duì)用戶是可見(jiàn)的,空狀態(tài)只能是暫時(shí)的。
static addEventListener(type: string, handler: Function)
通過(guò)監(jiān)聽(tīng) change 事件類型和提供處理程序,為應(yīng)用程序狀態(tài)變化添加一個(gè)處理程序。
static removeEventListener(type: string, handler: Function)
通過(guò)傳遞 change 事件類型和處理程序,刪除一個(gè)處理程序。
'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} />; }
},
];