React Native:如何检测应用程序是不是在启动时/从 AppSwitcher 关闭应用程序后进入前台?

Posted

技术标签:

【中文标题】React Native:如何检测应用程序是不是在启动时/从 AppSwitcher 关闭应用程序后进入前台?【英文标题】:React Native: How to detect if an app has come to the foreground on start/after closing the app from AppSwitcher?React Native:如何检测应用程序是否在启动时/从 AppSwitcher 关闭应用程序后进入前台? 【发布时间】:2021-12-31 03:37:21 【问题描述】:

我希望能够在我的 React Native 应用程序进入前台时订阅事件监听器。

React Native 有 AppState 这些 API,官方文档中有以下示例

const AppStateExample = () => 
  const appState = useRef(AppState.currentState);
  const [appStateVisible, setAppStateVisible] = useState(appState.current);

  useEffect(() => 
    const subscription = AppState.addEventListener("change", nextAppState => 
      if (
        appState.current.match(/inactive|background/) &&
        nextAppState === "active"
      ) 
        console.log("App has come to the foreground!");
      

      appState.current = nextAppState;
      setAppStateVisible(appState.current);
    );

    return () => 
      subscription.remove();
    ;
  , []);

  return (
      <Text>Current state is: appStateVisible</Text>
  );
;

我的问题是当应用程序第一次启动时,或者在我通过向上滑动从 AppSwitcher 关闭 ios 上的应用程序之后,这不起作用。

从 AppSwitcher 关闭应用后第一次启动时,如何检测状态变化?据我所知,在这种情况下,状态是background

【问题讨论】:

【参考方案1】:

尝试将 if 语句更改为如下内容:

  if (
    appState.current.match(/inactive|background/) &&
    nextAppState === 'active'
  ) 
    console.log('App has come to the foreground!');
   else 
    console.log('App state', nextAppState);
  

如果您启动应用程序然后向上滑动将其关闭,您应该会看到以下日志输出:

 LOG  Running "appstatetest" with "rootTag":1,"initialProps":
 LOG  App state active
 LOG  App state inactive
 LOG  App state background

应用程序首次启动时正在输出应用程序状态。当您开始向上滑动时,正在输出应用状态非活动状态,并在应用关闭时输出应用状态背景。

【讨论】:

以上是关于React Native:如何检测应用程序是不是在启动时/从 AppSwitcher 关闭应用程序后进入前台?的主要内容,如果未能解决你的问题,请参考以下文章