#鸿蒙通关秘籍#如何订阅进程内UIAbility的生命周期变化?

HarmonyOS
7h前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
CPU白云苍狗

通过ApplicationContext,可以实现对进程内UIAbility生命周期变化的订阅:

js import { AbilityConstant, AbilityLifecycleCallback, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { window } from '@kit.ArkUI'; import { BusinessError } from '@kit.BasicServicesKit';

export default class LifecycleAbility extends UIAbility { lifecycleId: number = -1;

onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { let abilityLifecycleCallback: AbilityLifecycleCallback = { onAbilityCreate(uiAbility) { hilog.info(0xFF00, '[LifecycleAbility]', onAbilityCreate: ${JSON.stringify(uiAbility.launchWant)}); }, // 其他生命周期回调函数... };

let applicationContext = this.context.getApplicationContext();
try {
  this.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback);
} catch (err) {
  let code = (err as BusinessError).code;
  let message = (err as BusinessError).message;
  hilog.error(0xFF00, '[LifecycleAbility]', `注册失败,代码: ${code}, 信息: ${message}`);
}

}

onDestroy(): void { let applicationContext = this.context.getApplicationContext(); try { applicationContext.off('abilityLifecycle', this.lifecycleId); } catch (err) { let code = (err as BusinessError).code; let message = (err as BusinessError).message; hilog.error(0xFF00, '[LifecycleAbility]', 取消注册失败,代码: ${code}, 信息: ${message}); } } }

通过注册和取消注册相应的回调函数,可以处理UILifecycle的生命周期事件。


分享
微博
QQ
微信
回复
4h前
相关问题
应用生命周期流转
614浏览 • 1回复 待解决