OpenHarmony开源社区
直播中

刘满贵

7年用户 1450经验值
私信 关注
[经验]

HarmonyOS ARK ets语言实现返回键退出的教程

代码运行

思路:

定义一个改变类型的时间变量,然后点击时间差,如果大于 2 提示“再按一次”类似,然后点击时间与关闭应用程序,秒

import prompt from '@system.prompt';

import app from '@system.app'

@Entry

@Component

struct 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%')

}

}

运行效果

原作者:我不是猫了

回帖(2)

玩硬件的女孩纸

2022-5-26 11:12:38
优秀!感谢分享!
举报

陈皓雷

2022-5-26 18:54:25
谢谢分享,很有用
举报

更多回帖

发帖
×
20
完善资料,
赚取积分