HarmonyOS 小游戏《对战五子棋》开发第36篇 - EntryAbility生命周期
·
从创建到销毁——理解鸿蒙应用的生命周期

EntryAbility完整代码
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
console.info('[Gomoku] EntryAbility onCreate');
}
onDestroy(): void {
console.info('[Gomoku] EntryAbility onDestroy');
}
onWindowStageCreate(windowStage: window.WindowStage): void {
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
console.error(`[Gomoku] Failed: ${err.code}`);
return;
}
});
}
onWindowStageDestroy(): void { }
onForeground(): void { }
onBackground(): void { }
}
生命周期图解
onCreate → onWindowStageCreate → onForeground
↓
[用户使用]
↓
onBackground ← → onForeground
↓
onWindowStageDestroy → onDestroy
六个回调
| 回调 | 时机 | 用途 |
|---|---|---|
| onCreate | Ability创建 | 初始化数据 |
| onWindowStageCreate | 窗口创建 | 加载首页 |
| onForeground | 进入前台 | 恢复状态 |
| onBackground | 进入后台 | 保存状态 |
| onWindowStageDestroy | 窗口销毁 | 释放资源 |
| onDestroy | Ability销毁 | 最终清理 |
loadContent
windowStage.loadContent('pages/Index', (err) => { ... });
加载pages/Index作为窗口内容——这个路径必须在main_pages.json中注册。
总结
理解UIAbility生命周期让开发者能在正确的时机执行正确的逻辑。本项目在回调中只输出日志,实际应用可在onBackground保存进度、onForeground恢复状态。
更多推荐




所有评论(0)