onForeground(): void { // Ability has brought to foreground hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground'); } onBackground(): void { // Ability has back to background hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground'); }
onWindowStageCreate(windowStage: window.WindowStage): void { // Main window is created, set main page for this ability hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); // 设置WindowStage的事件订阅(切到前台/切到后台) try { windowStage.on('windowStageEvent', (data) => { let stageEventType: window.WindowStageEventType = data; switch (stageEventType) { // 切到前台 case window.WindowStageEventType.SHOWN: console.log(`windowStage foreground.`); // ... break; // 切到后台 case window.WindowStageEventType.HIDDEN: console.log(`windowStage background.`); // ... break; default: break; } }); } catch (exception) { console.log(`Failed to enable the listener for window stage event changes. Cause: ${JSON.stringify(exception)}`); } windowStage.loadContent('pages/Index', (err) => { if (err.code) { hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err)); return; } hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.'); }); }
build() { RelativeContainer() { Button('获取信息').onClick(() => { let applicationContext = this.getUIContext().getHostContext()?.getApplicationContext(); applicationContext?.getRunningProcessInformation().then((data) => { console.log(`The process running information is: ${JSON.stringify(data)}`); }); }) } .height('100%') .width('100%') }
使用EventHub发送通知this.context.eventHub.emit('onForeground');。
eventFunc() { // 响应进入前台方法 // ... } aboutToAppear(): void { // 以eventHub为例,订阅事件 this.getUIContext().getHostContext()?.eventHub.on('onForeground', this.eventFunc); } aboutToDisappear(): void { this.getUIContext().getHostContext()?.eventHub.off('onForeground', this.eventFunc); }