Skip to main content

AppState

AppState 可以告诉你应用是在前台还是后台,并在状态发生变化时通知你。

¥AppState can tell you if the app is in the foreground or background, and notify you when the state changes.

AppState 经常用于确定处理推送通知时的意图和正确行为。

¥AppState is frequently used to determine the intent and proper behavior when handling push notifications.

应用状态

¥App States

  • active - 该应用正在前台运行

    ¥active - The app is running in the foreground

  • background - 该应用正在后台运行。用户是:

    ¥background - The app is running in the background. The user is either:

    • 在另一个应用中

      ¥in another app

    • 在主屏幕上

      ¥on the home screen

    • [Android] 在另一个 Activity 上(即使它是由你的应用启动的)

      ¥[Android] on another Activity (even if it was launched by your app)

  • [iOS] inactive - 这是在前台和后台之间转换时以及在不活动期间(例如进入多任务视图、打开通知中心或有来电时)发生的状态。

    ¥[iOS] inactive - This is a state that occurs when transitioning between foreground & background, and during periods of inactivity such as entering the multitasking view, opening the Notification Center or in the event of an incoming call.

欲了解更多信息,请参阅 苹果的文档

¥For more information, see Apple's documentation

基本用法

¥Basic Usage

要查看当前状态,你可以检查 AppState.currentState,它将保持最新状态。然而,currentState 在启动时将为空,而 AppState 通过桥取回它。

¥To see the current state, you can check AppState.currentState, which will be kept up-to-date. However, currentState will be null at launch while AppState retrieves it over the bridge.

这个例子只会显示“当前状态是:active”,因为应用仅在处于 active 状态时对用户可见,并且 null 状态只会暂时发生。如果你想试验代码,我们建议你使用自己的设备而不是嵌入式预览。

¥This example will only ever appear to say "Current state is: active" because the app is only visible to the user when in the active state, and the null state will happen only momentarily. If you want to experiment with the code we recommend to use your own device instead of embedded preview.


参考

¥Reference

事件

¥Events

change

当应用状态发生更改时会收到此事件。使用 当前应用状态值 之一调用监听器。

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

memoryWarning

该事件用于需要抛出内存警告或释放内存的情况。

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

focus
Android

当应用获得焦点时收到(用户正在与应用交互)。

¥Received when the app gains focus (the user is interacting with the app).

blur
Android

当用户未主动与应用交互时收到。在用户拉下 通知抽屉 的情况下很有用。AppState 不会改变,但 blur 事件将被触发。

¥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.

方法

¥Methods

addEventListener()

static addEventListener(
type: AppStateEvent,
listener: (state: AppStateStatus) => void,
): NativeEventSubscription;

设置一个函数,只要 AppState 上发生指定的事件类型,就会调用该函数。eventType 的有效值为 以上所列。返回 EventSubscription

¥Sets up a function that will be called whenever the specified event type on AppState occurs. Valid values for eventType are listed above. Returns the EventSubscription.

属性

¥Properties

currentState

static currentState: AppStateStatus;