Harmony HMRouter HMLifecycle 基本使用

122 阅读1分钟

1 声明 HMLifecycle

@HMLifecycle({lifecycleName: 'ExitAppLifecycle'})
export class ExitAppLifecycle implements IHMLifecycle {
  private lastTime: number = 0;
  onBackPressed(ctx: HMLifecycleContext): boolean {
    let time = new Date().getTime();
    if(time - this.lastTime > 1000) {
      this.lastTime = time;
      ctx.uiContext.getPromptAction().showToast({
        message: CommonConstants.EXIT_TOAST,
        duration: 1000
      });
      return true;
    } else {
      return false;
    }
  }
}

这是官方demo中声明的首页二次点击退出的Lifecycle。当用户处于首页并且按返回键会先走onBackPressed方法。返回true,正常走返回键的逻辑,返回false取消这次操作。

2 使用

@HMRouter({pageUrl: PageConstant.PRODUCT_CONTENT,lifecycle:'ExitAppLifecycle'})
@Component
export struct ProductContent {}

只需要在HMRouter注解中设置lifecycle字段值为ExitAppLifecycle就可以了。

3 除了onBackPressed ,IHMLifecycle 还可以监听其他的生命周期方法,如下

export interface IHMLifecycle {
    onPrepare?(ctx: HMLifecycleContext): void;
    onAppear?(ctx: HMLifecycleContext): void;
    onDisAppear?(ctx: HMLifecycleContext): void;
    onShown?(ctx: HMLifecycleContext): void;
    onHidden?(ctx: HMLifecycleContext): void;
    onWillAppear?(ctx: HMLifecycleContext): void;
    onWillDisappear?(ctx: HMLifecycleContext): void;
    onWillShow?(ctx: HMLifecycleContext): void;
    onWillHide?(ctx: HMLifecycleContext): void;
    onReady?(ctx: HMLifecycleContext): void;
    onBackPressed?(ctx: HMLifecycleContext): boolean;
}

4 使用Lifecycle 统计页面的展示时长

export class PageDurationLifecycle implements IHMLifecycle {
  private timeMap: Map<string, number> = new Map();
  onShown(ctx: HMLifecycleContext): void {
    const pageName = ctx.navContext?.pathInfo.name;
    if(pageName) {
      this.timeMap.set(pageName, new Date().getTime());
    }
  }

  onHidden(ctx: HMLifecycleContext): void {
    const pageName = ctx.navContext?.pathInfo.name;
    if(pageName && this.timeMap.has(pageName)) {
      const duration = new Date().getTime() - (this.timeMap.get(pageName) as number);
      this.timeMap.delete(pageName);
      console.log(`Page ${pageName} stay ${duration} ms`);
    }
  }
}