跳到主要内容
新架构实战课 实操 + 基建 + 原理全维度包揽,抢先掌握 React Native 新架构精髓 立即查看 >

AppState

AppState能告诉你应用当前是在前台还是在后台,并且能在状态变化的时候通知你。

AppState 通常在处理推送通知的时候用来决定内容和对应的行为。

App States

  • active - 应用正在前台运行
  • background - 应用正在后台运行。用户可能面对以下几种情况:
    • 在别的应用中
    • 停留在桌面
    • 对 Android 来说还可能处在另一个Activity中(即便是由你的应用拉起的)
  • [iOS] inactive - 此状态表示应用正在前后台的切换过程中,或是处在系统的多任务视图,又或是处在来电状态中。

要了解更多信息,可以阅读Apple 的文档

基本用法

要获取当前的状态,你可以使用AppState.currentState,这个变量会一直保持更新。不过在启动的过程中,currentState可能为 null,直到AppState从原生代码得到通知为止。

If you don't want to see the AppState update from active to inactive on iOS you can remove the state variable and use the appState.current value.

上面的这个例子只会显示"Current state is: active",这是因为应用只有在active状态下才能被用户看到。并且 null 状态只会在一开始的一瞬间出现。If you want to experiment with the code we recommend to use your own device instead of embedded preview.


文档

事件

blur

[Android only] Received when the user is not actively interacting with the app. Useful in situations when the user pulls down the notification drawer. AppState won't change but the blur event will get fired.

change

This even is received when the app state has changed. The listener is called with one of the current app state values.

focus

[Android only] Received when the app gains focus (the user is interacting with the app).

memoryWarning

This event is used in the need of throwing memory warning or releasing it.

方法

addEventListener()

addEventListener(type, handler);

添加一个监听函数,用于监听应用状态的变化。type 参数应填change

TODO: now that AppState is a subclass of NativeEventEmitter, we could deprecate addEventListener and removeEventListener and use addListener and listener.remove() directly. That will be a breaking change though, as both the method and event names are different (addListener events are currently required to be globally unique).


removeEventListener()

removeEventListener(type, handler);

移除一个监听函数。type 参数应填change

属性

currentState

AppState.currentState;