HarmonyOS 前后台进程切换时机?

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

阅读 703
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) ?? '');
  });
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进