1e41f4b71Sopenharmony_ci# PageAbility的生命周期 2e41f4b71Sopenharmony_ci 3e41f4b71Sopenharmony_ci 4e41f4b71Sopenharmony_ciPageAbility生命周期是PageAbility被调度到INACTIVE、ACTIVE、BACKGROUND等各个状态的统称。PageAbility生命周期流转及状态说明见如下图1、表1所示。 5e41f4b71Sopenharmony_ci 6e41f4b71Sopenharmony_ci **图1** PageAbility生命周期流转 7e41f4b71Sopenharmony_ci 8e41f4b71Sopenharmony_ci 9e41f4b71Sopenharmony_ci 10e41f4b71Sopenharmony_ci 11e41f4b71Sopenharmony_ci **表1** PageAbility生命周期状态说明 12e41f4b71Sopenharmony_ci 13e41f4b71Sopenharmony_ci| 生命周期状态 | 生命周期状态说明 | 14e41f4b71Sopenharmony_ci| -------- | -------- | 15e41f4b71Sopenharmony_ci| UNINITIALIZED | 未初始状态,为临时状态,PageAbility被创建后会由UNINITIALIZED状态进入INITIAL状态。 | 16e41f4b71Sopenharmony_ci| INITIAL | 初始化状态,也表示停止状态,表示当前PageAbility未运行,PageAbility被启动后由INITIAL态进入INACTIVE状态。 | 17e41f4b71Sopenharmony_ci| INACTIVE | 失去焦点状态,表示当前窗口已显示但是无焦点状态。 | 18e41f4b71Sopenharmony_ci| ACTIVE | 前台激活状态,表示当前窗口已显示,并获取焦点。 | 19e41f4b71Sopenharmony_ci| BACKGROUND | 后台状态,表示当前PageAbility退到后台,PageAbility在被销毁后由BACKGROUND状态进入INITIAL状态,或者重新被激活后由BACKGROUND状态进入ACTIVE状态。 | 20e41f4b71Sopenharmony_ci 21e41f4b71Sopenharmony_ci 22e41f4b71Sopenharmony_ci应用开发者可以在app.js/app.ets中实现生命周期相关回调函数,PageAbility生命周期相关回调函数见下表。 23e41f4b71Sopenharmony_ci 24e41f4b71Sopenharmony_ci 25e41f4b71Sopenharmony_ci **表2** PageAbility生命周期回调接口说明 26e41f4b71Sopenharmony_ci 27e41f4b71Sopenharmony_ci| 接口名 | 接口描述 | 28e41f4b71Sopenharmony_ci| -------- | -------- | 29e41f4b71Sopenharmony_ci| onCreate() | Ability第一次启动创建Ability时调用onCreate方法,开发者可以在该方法里做一些应用初始化工作。 | 30e41f4b71Sopenharmony_ci| onDestroy() | 应用退出,销毁Ability对象前调用onDestroy方法,开发者可以在该方法里做一些回收资源、清空缓存等应用退出前的准备工作。 | 31e41f4b71Sopenharmony_ci| onActive() | Ability切换到前台,并且已经获取焦点时调用onActive方法。 | 32e41f4b71Sopenharmony_ci| onInactive() | Ability失去焦点时调用onInactive方法,Ability在进入后台状态时会先失去焦点,再进入后台。 | 33e41f4b71Sopenharmony_ci| onShow() | Ability由后台不可见状态切换到前台可见状态调用onShow方法,此时用户在屏幕可以看到该Ability。 | 34e41f4b71Sopenharmony_ci| onHide() | Ability由前台切换到后台不可见状态时调用onHide方法,此时用户在屏幕看不到该Ability。 | 35e41f4b71Sopenharmony_ci 36e41f4b71Sopenharmony_ci 37e41f4b71Sopenharmony_ciPageAbility生命周期回调与生命周期状态的关系如下图所示。 38e41f4b71Sopenharmony_ci 39e41f4b71Sopenharmony_ci **图2** PageAbility生命周期回调与生命周期状态的关系 40e41f4b71Sopenharmony_ci 41e41f4b71Sopenharmony_ci 42e41f4b71Sopenharmony_ci 43e41f4b71Sopenharmony_ci 44e41f4b71Sopenharmony_ci> **说明:** 45e41f4b71Sopenharmony_ci> 46e41f4b71Sopenharmony_ci> 1. PageAbility的生命周期回调均为同步接口。 47e41f4b71Sopenharmony_ci> 2. 目前app.js环境中仅支持onCreate和onDestroy回调,app.ets环境支持全量生命周期回调。 48