AppState
AppState
能告诉你应用当前是在前台还是在后台,并且能在状态变化的时候通知你。
AppState 通常在处理推送通知的时候用来决定内容和对应的行为。
App States
active
- 应用正在前台运行background
- 应用正在后台运行。用户可能面对以下几种情况:- 在别的应用中
- 停留在桌面
- 对 Android 来说还可能处在另一个
Activity
中(即便是由你的应用拉起的)
- [iOS]
inactive
- 此状态表示应用正在前后台的切换过程中,或是处在系统的多任务视图,又或是处在来电状态中。
要了解更多信息,可以阅读Apple 的文档。
基本用法
要获取当前的状态,你可以使用AppState.currentState
,这个变量会一直保持更新。不过在启动的过程中,currentState
可能为 null,直到AppState
从原生代码得到通知为止。
- 函数式组件
- Class 组件
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);