鸿蒙项目实战(六):HMRouter实现两次返回退出应用

1、定义一个生命周期类ExitAppLifecycle实现IHMLifecycle接口

复制代码
import { HMLifecycle, HMLifecycleContext, IHMLifecycle } from '@hadss/hmrouter';

@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 > 2000) {
      this.lastTime = time;
      ctx.uiContext.getPromptAction().showToast({
        message: '再按一次返回键回到桌面',
        duration: 2000
      });
      return true;
    } else {
      return false;
    }
  }
}
复制代码

2、相关页面关联该生命周期类

// 绑定生命周期及自定义转场动画
@HMRouter({ pageUrl: 'Main', singleton:true,lifecycle: 'ExitAppLifecycle', animator: 'pageAnimator' })
@Component
// 注意HMRouter页面需要export
export struct Main {
  builder{}  
} 
posted @   听着music睡  阅读(91)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2016-11-21 Android项目实战(二十八):Zxing二维码实现及优化
点击右上角即可分享
微信分享提示