HarmonyOS 前后台进程切换时机?

程序进入后台运行时,想做一些操作,进入前台时,再做一些操作,如何做到?

阅读 708
1 个回答

可以使用window.on("windowEvent")监听,具体文档请参考:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-window-V5

代码结构如下:

onWindowStageCreate(windowStage: window.WindowStage) {
  // Main window is created, set main page for this ability
  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
  windowStage.loadContent('pages/AppGeoLocation', (err, data) => {
    if (err.code) {
      hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
      return;
    }
    windowStage.getMainWindowSync().on("windowEvent", (data) => {
      if (data == window.WindowEventType.WINDOW_SHOWN) {
        console.log("App is in Foreground")
      }
      else if (data == window.WindowEventType.WINDOW_HIDDEN) {
        console.log("App is in Background")
      }
    })
    hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
  });
}