鸿蒙系统生命周期详解
2026年3月17日大约 5 分钟
鸿蒙系统生命周期详解
鸿蒙系统(HarmonyOS)的生命周期主要分为以下几个层次:
- 应用生命周期(UIAbility)
- 页面生命周期(Page)
- 组件生命周期(Component)
- 其他生命周期(TaskPool、Worker等)
1. 应用生命周期(UIAbility)
UIAbility 是应用的基本调度单元,每个 UIAbility 有自己的生命周期。
生命周期状态
| 状态 | 说明 |
|---|---|
| Create | 应用创建时触发 |
| WindowStageCreate | 窗口创建时触发 |
| WindowStageFocus | 窗口获取焦点时触发 |
| WindowStageBlur | 窗口失去焦点时触发 |
| WindowStageDestroy | 窗口销毁时触发 |
| Destroy | 应用销毁时触发 |
生命周期流程图
Create → WindowStageCreate → [WindowStageFocus ↔ WindowStageBlur] → WindowStageDestroy → Destroy代码示例
import UIAbility from "@ohos.app.ability.UIAbility";
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
console.log("应用创建");
// 初始化应用级资源
}
onWindowStageCreate(windowStage) {
console.log("窗口创建");
// 设置窗口内容
windowStage.setUIContent("pages/Index");
}
onWindowStageFocus() {
console.log("窗口获取焦点");
}
onWindowStageBlur() {
console.log("窗口失去焦点");
}
onWindowStageDestroy() {
console.log("窗口销毁");
// 清理窗口相关资源
}
onDestroy() {
console.log("应用销毁");
// 清理应用级资源
}
onNewWant(want, launchParam) {
console.log("新的Want");
// 处理新的启动意图
}
onDump(params) {
return ["params: " + params];
}
}启动模式
UIAbility 支持三种启动模式:
| 模式 | 说明 |
|---|---|
| singleton | 单实例,默认值 |
| multiton | 多实例 |
| specified | 指定实例 |
{
"abilities": [
{
"name": "EntryAbility",
"launchType": "singleton", // 单实例
"skills": [
{
"actions": ["ohos.want.action.home"]
}
]
}
]
}2. 页面生命周期(Page)
页面生命周期是指 @Entry 组件所在的页面的生命周期。
生命周期状态
| 状态 | 说明 |
|---|---|
| onPageShow | 页面显示时触发 |
| onPageHide | 页面隐藏时触发 |
| onBackPress | 返回按钮按下时触发 |
代码示例
@Entry
@Component
struct PageLifecycle {
onPageShow() {
console.log('页面显示')
// 页面可见时执行
}
onPageHide() {
console.log('页面隐藏')
// 页面不可见时执行
}
onBackPress() {
console.log('返回按钮按下')
// 返回按钮事件处理
// return true 表示拦截默认行为
return false
}
build() {
Column() {
Text('页面生命周期示例')
}
}
}页面跳转生命周期
页面A onPageHide → 页面B onPageShowimport router from '@ohos.router'
// 页面A
@Entry
@Component
struct PageA {
onPageShow() {
console.log('PageA onPageShow')
}
onPageHide() {
console.log('PageA onPageHide')
}
build() {
Column() {
Button('跳转到PageB')
.onClick(() => {
router.pushUrl({ url: 'pages/PageB' })
})
}
}
}
// 页面B
@Entry
@Component
struct PageB {
onPageShow() {
console.log('PageB onPageShow')
}
onPageHide() {
console.log('PageB onPageHide')
}
build() {
Column() {
Text('PageB')
Button('返回')
.onClick(() => {
router.back()
})
}
}
}3. 组件生命周期(Component)
@Component 装饰的组件有自己的生命周期。
生命周期状态
| 状态 | 说明 |
|---|---|
| aboutToAppear | 组件即将出现时触发 |
| aboutToDisappear | 组件即将消失时触发 |
| onAreaChange | 组件区域变化时触发 |
| onVisibleChange | 组件可见性变化时触发 |
aboutToAppear 和 aboutToDisappear
@Component
struct LifecycleComponent {
aboutToAppear() {
console.log('组件即将出现')
// 初始化组件数据
// 发起网络请求等
}
aboutToDisappear() {
console.log('组件即将消失')
// 清理资源
// 取消订阅等
}
build() {
Column() {
Text('组件生命周期')
}
}
}onAreaChange
@Component
struct AreaChangeComponent {
@State width: number = 100
@State height: number = 100
build() {
Column() {
Rect()
.width(this.width)
.height(this.height)
.fill('#FF0000')
.onAreaChange(oldValue: Area, newValue: Area) {
console.log(`区域变化: ${JSON.stringify(oldValue)} -> ${JSON.stringify(newValue)}`)
}
Button('改变大小')
.onClick(() => {
this.width = 200
this.height = 200
})
}
}
}onVisibleChange
@Component
struct VisibleChangeComponent {
@State isVisible: boolean = true
build() {
Column() {
if (this.isVisible) {
Text('可见区域')
.onVisibleChange(visible: boolean) {
console.log(`可见性变化: ${visible}`)
}
}
Button('切换可见性')
.onClick(() => {
this.isVisible = !this.isVisible
})
}
}
}完整示例
@Entry
@Component
struct FullLifecycle {
@State message: string = 'Hello'
aboutToAppear() {
console.log('aboutToAppear - 组件即将出现')
}
onPageShow() {
console.log('onPageShow - 页面显示')
}
onPageHide() {
console.log('onPageHide - 页面隐藏')
}
aboutToDisappear() {
console.log('aboutToDisappear - 组件即将消失')
}
build() {
Column({ space: 20 }) {
Text(this.message)
.fontSize(30)
Button('修改消息')
.onClick(() => {
this.message = 'World'
})
}
.width('100%')
.height('100%')
}
}4. 其他生命周期
TaskPool 生命周期
import taskpool from '@ohos.taskpool'
@Concurrent
function taskFunction(data: number): number {
return data * 2
}
async function useTaskPool() {
// 创建任务
const task = new taskpool.Task(taskFunction, 100)
// 执行任务
const result = await taskpool.execute(task)
console.log('TaskPool执行结果:', result)
}Worker 生命周期
// Worker 线程
import Worker from "@ohos.worker";
const worker = new Worker("workers/worker.ts");
worker.onmessage = (message) => {
console.log("收到消息:", message.data);
};
worker.postMessage("Hello from main thread");
worker.terminate(); // 终止 Worker应用上下文生命周期
import featureAbility from "@ohos.ability.featureAbility";
// 获取应用上下文
const context = featureAbility.getContext();
// 获取应用信息
context.applicationInfo;
// 获取应用数据目录
context.dataDir;
// 获取应用配置
context.config;生命周期执行顺序
应用启动
1. UIAbility.onCreate()
2. UIAbility.onWindowStageCreate()
3. UIAbility.onWindowStageFocus()
4. Component.aboutToAppear()
5. Page.onPageShow()应用切换到后台
1. Page.onPageHide()
2. Component.aboutToDisappear()
3. UIAbility.onWindowStageBlur()应用切换到前台
1. UIAbility.onWindowStageFocus()
2. Component.aboutToAppear()
3. Page.onPageShow()应用销毁
1. Page.onPageHide()
2. Component.aboutToDisappear()
3. UIAbility.onWindowStageDestroy()
4. UIAbility.onDestroy()生命周期注意事项
- 不要在生命周期中进行耗时操作:以免影响用户体验
- 及时清理资源:在 aboutToDisappear 或 onDestroy 中清理
- 注意内存泄漏:取消订阅、关闭定时器等
- 状态恢复:使用 onPageShow 恢复页面状态
- 数据持久化:使用 aboutToDisappear 保存必要数据
生命周期与状态管理
| 生命周期 | 推荐使用的状态管理 |
|---|---|
| onCreate | @StorageLink 初始化 |
| aboutToAppear | @State 数据加载 |
| onPageShow | @Link 数据刷新 |
| onPageHide | @Prop 数据保存 |
| aboutToDisappear | 清理资源 |
| onDestroy | @StorageLink 数据持久化 |
最佳实践
正确初始化
@Entry
@Component
struct BestPractice {
@State data: string = ''
@StorageLink('cache') cache: string = ''
aboutToAppear() {
// 从存储中恢复数据
this.data = this.cache
}
onPageHide() {
// 页面隐藏时保存数据
this.cache = this.data
}
aboutToDisappear() {
// 清理资源
console.log('清理资源')
}
build() {
Column() {
Text(this.data)
}
}
}避免内存泄漏
@Component
struct AvoidLeak {
timer: number = 0
subscription: any = null
aboutToAppear() {
// 错误的做法:重复创建定时器
this.timer = setInterval(() => {
console.log('timer')
}, 1000)
}
aboutToDisappear() {
// 正确的做法:清理定时器
if (this.timer) {
clearInterval(this.timer)
}
if (this.subscription) {
this.subscription.unsubscribe()
}
}
build() {
Column() {
Text('避免内存泄漏')
}
}
}总结
鸿蒙系统的生命周期体系完善,开发者需要理解不同层级的生命周期:
- UIAbility 生命周期:应用级别,管理应用的整体状态
- Page 生命周期:页面级别,管理页面的显示隐藏
- Component 生命周期:组件级别,管理组件的创建销毁
合理利用生命周期可以:
- 优化应用性能
- 避免内存泄漏
- 提升用户体验
- 正确管理资源