而 HarmonyOS 中的UI组件 UIAbility 也和 Android 中的 Activity 有着类似的生命周期:
import UIAbility from ‘@ohos.app.ability.UIAbility’;
import hilog from ‘@ohos.hilog’;
import window from ‘@ohos.window’;
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
// 组件创建
hilog.info(0x0000, ‘testTag’, ‘%{public}s’, ‘Ability onCreate’);
}
onDestroy() {
// 组件销毁
hilog.info(0x0000, ‘testTag’, ‘%{public}s’, ‘Ability onDestroy’);
}
onWindowStageCreate(windowStage: window.WindowStage) {
// window 创建
// Main window is created, set main page for this ability
hilog.info(0x0000, ‘testTag’, ‘%{public}s’, ‘Ability onWindowStageCreate’);
// 设置布局,显示 ets/pages/Index.ets 的布局
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
});
}
onWindowStageDestroy() {
// window 销毁
// Main window is destroyed, release UI related resources
hilog.info(0x0000, ‘testTag’, ‘%{public}s’, ‘Ability onWindowStageDestroy’);
}
onForeground() {
// 进入前台
// Ability has brought to foreground
hilog.info(0x0000, ‘testTag’, ‘%{public}s’, ‘Ability onForeground’);
}
onBackground() {
// 进入后台
// Ability has back to background
hilog.info(0x0000, ‘testTag’, ‘%{public}s’, ‘Ability onBackground’);
}
}
HarmonyOS 的 UIAbility 没有 Android 中 Activity 的 onResume onPause 生命周期回调方法,当然如果需要的话还是有方案可以实现的,需要在 onWindowStageCreate 方法里,通过 windowStage 实现:
onWindowStageCreate(windowStage: window.WindowStage) {
windowStage.on(‘windowStageEvent’, (event) => {
// event 取值为枚举类型 window.WindowStageEventType
if(event === window.WindowStageEventType.ACTIVE) {
// 获取焦点
} else {
// 失去焦点
}
})
}