iOS 应用程序状态

AppStateIOS 可以告诉你应用程序是在前台还是在后台,而且状态更新时会通知你。 在处理推送通知时,AppStateIOS 经常被用于判断目标和适当的行为。

iOS 应用程序状态

  • Active - 应用程序在前台运行
  • Background - 应用程序在后台运行。用户正在使用另一个应用程序或者在主屏幕上。
  • Inactive - 这是一种过渡状态,目前不会在React Native的应用程序上发生。

想要获取更多的信息,见 Apple’s documentation

基本用法

为了查看当前的状态,你可以检查 AppStateIOS.currentState,该方法会一直保持最新状态。然而,当 AppStateIOS 在桥接器上检索currentState时,在启动时它将会为空。

1. getInitialState: function() {
2. return {
3. currentAppState: AppStateIOS.currentState,
4. };
5. },
6. componentDidMount: function() {
7. AppStateIOS.addEventListener('change', this._handleAppStateChange);
8. },
9. componentWillUnmount: function() {
10. AppStateIOS.removeEventListener('change', this._handleAppStateChange);
11. },
12. _handleAppStateChange: function(currentAppState) {
13. this.setState({ currentAppState, });
14. },
15. render: function() {
16. return (
17. <Text>Current state is: {this.state.currentAppState}</Text>
18. );
19. },

这个例子似乎只能说”当前状态是:活跃的”因为在 active 状态时,应用程序只对用户是可见的,空状态只能是暂时的。

方法

static addEventListener(type: string, handler: Function)

通过监听 change 事件类型和提供处理程序,为应用程序状态变化添加一个处理程序。

static removeEventListener(type: string, handler: Function)

通过传递 change 事件类型和处理程序,删除一个处理程序。

例子

Edit on GitHub

1. 'use strict';
2. var React = require('react-native');
3. var {
4. AppStateIOS,
5. Text,
6. View
7. } = React;
8. var AppStateSubscription = React.createClass({
9. getInitialState() {
10. return {
11. appState: AppStateIOS.currentState,
12. previousAppStates: [],
13. };
14. },
15. componentDidMount: function() {
16. AppStateIOS.addEventListener('change', this._handleAppStateChange);
17. },
18. componentWillUnmount: function() {
19. AppStateIOS.removeEventListener('change', this._handleAppStateChange);
20. },
21. _handleAppStateChange: function(appState) {
22. var previousAppStates = this.state.previousAppStates.slice();
23. previousAppStates.push(this.state.appState);
24. this.setState({
25. appState,
26. previousAppStates,
27. });
28. },
29. render() {
30. if (this.props.showCurrentOnly) {
31. return (
32. <View>
33. <Text>{this.state.appState}</Text>
34. </View>
35. );
36. }
37. return (
38. <View>
39. <Text>{JSON.stringify(this.state.previousAppStates)}</Text>
40. </View>
41. );
42. }
43. });
44. exports.title = 'AppStateIOS';
45. exports.description = 'iOS app background status';
46. exports.examples = [
47. {
48. title: 'AppStateIOS.currentState',
49. description: 'Can be null on app initialization',
50. render() { return <Text>{AppStateIOS.currentState}</Text>; }
51. },
52. {
53. title: 'Subscribed AppStateIOS:',
54. description: 'This changes according to the current state, so you can only ever see it rendered as "active"',
55. render(): ReactElement { return <AppStateSubscription showCurrentOnly={true} />; }
56. },
57. {
58. title: 'Previous states:',
59. render(): ReactElement { return <AppStateSubscription showCurrentOnly={false} />; }
60. },
61. ];