typescript
复制代码
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';
const TAG: string = '[EntryAbility]';
const DOMAIN_NUMBER: number = 0xFF00;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
// 页面初始化
}
// ...
onWindowStageCreate(windowStage: window.WindowStage): void {
// 设置WindowStage的事件订阅(获焦/失焦、切到前台/切到后台、前台可交互/前台不可交互)
try {
windowStage.on('windowStageEvent', (data) => {
let stageEventType: window.WindowStageEventType = data;
switch (stageEventType) {
case window.WindowStageEventType.SHOWN: // 切到前台
hilog.info(DOMAIN_NUMBER, TAG, `windowStage foreground.`);
break;
case window.WindowStageEventType.ACTIVE: // 获焦状态
hilog.info(DOMAIN_NUMBER, TAG, `windowStage active.`);
break;
case window.WindowStageEventType.INACTIVE: // 失焦状态
hilog.info(DOMAIN_NUMBER, TAG, `windowStage inactive.`);
break;
case window.WindowStageEventType.HIDDEN: // 切到后台
hilog.info(DOMAIN_NUMBER, TAG, `windowStage background.`);
break;
case window.WindowStageEventType.RESUMED: // 前台可交互状态
hilog.info(DOMAIN_NUMBER, TAG, `windowStage resumed.`);
break;
case window.WindowStageEventType.PAUSED: // 前台不可交互状态
hilog.info(DOMAIN_NUMBER, TAG, `windowStage paused.`);
break;
default:
break;
}
});
} catch (exception) {
hilog.error(DOMAIN_NUMBER, TAG,
`Failed to enable the listener for window stage event changes. Cause: ${JSON.stringify(exception)}`);
}
hilog.info(DOMAIN_NUMBER, TAG, `%{public}s`, `Ability onWindowStageCreate`);
// 设置UI加载
windowStage.loadContent('pages/Index', (err, data) => {
// ...
});
}
onForeground(): void {
// 申请系统需要的资源,或者重新申请在onBackground()中释放的资源
}
onBackground(): void {
// 释放UI不可见时无用的资源,或者在此回调中执行较为耗时的操作
// 例如状态保存等
}
onWindowStageWillDestroy(windowStage: window.WindowStage) {
// 释放通过windowStage对象获取的资源
// 在onWindowStageWillDestroy()中注销WindowStage事件订阅(获焦/失焦、切到前台/切到后台、前台可交互/前台不可交互)
try {
if (this.windowStage) {
this.windowStage.off('windowStageEvent');
}
} catch (err) {
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
hilog.error(DOMAIN_NUMBER, TAG, `Failed to disable the listener for windowStageEvent. Code is ${code}, message is ${message}`);
}
}
onWindowStageDestroy() {
// 释放UI资源
}
onDestroy() {
// 系统资源的释放、数据的保存等
}
}