【HarmonyOS】【ARK UI】HarmonyOS ets语言怎么实现双击返回键退出
参考资料
【Harmony OS】【ARK UI】Date 基本操作
自定义组件生命周期回调函数
弹窗
代码运行
思路:
定义一个全局变量,判断点击时间与上一次点击时间差,若大于2秒则提示‘再按一次退出程序’字样,小于2秒退出应用,代码如下
import prompt from '@system.prompt';import app from '@system.app'@Entry@Componentstruct Index { //todo 定义全局变量 @State exitTime: number= 0; private onBackPress() { this.ExitApp(); return true; } public ExitApp() { //todo 判断点击时间与上一次点击时间差,若大于5秒则提示‘再按一次退出程序’字样 if ((new Date().getTime() - this.exitTime) > 5000) { prompt.showToast({ message: '再按一次退出程序', duration: 2000, }); this.exitTime = new Date().getTime(); } else { //todo 小于5秒退出应用 app.terminate(); } } build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Text('双击返回app退出') .fontSize(40) .height(200) .width("100%") .textAlign(TextAlign.Center) .fontWeight(FontWeight.Bold) } .width('100%') .height('100%') }}
运行效果
欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh