鸿蒙应用开发小例-计时器小工具

实现效果

实现思路

整个小工具放在一个自定义弹窗内,弹窗右上角是关闭按钮,中间显示格式化的计时时间,底部显示操作按钮,按钮根据状态切换开始和停止。

点击开始按钮,开始计时,按钮切换为停止按钮。

点击停止按钮,停止计时,按钮切换为开始按钮。

代码实现

以下只列出了核心代码,省略了无关的组件和样式等细节。

UI结构
Column() {
    Row() {
        Text(this.format(this.timeCount))
    }
    Row() {
        if (!this.isCounting) {
            Button() {
                Image($r('app.media.play'))
            }
            .onClick(() => {
                this.start()
            })
        } else {
            Button() {
                Image($r('app.media.stop'))
            }
            .onClick(() => {
                this.stop()
            })
        }
    }
}

timeCount:计时时间,通过format方法格式化。

isCounting:用于切换显示开始和停止按钮。

format方法中使用了dayjs库格式化时间。

  timer: number | null = null
  @State timeCount: number = 0
  @State isCounting: boolean = false
  stop = () => {
    clearInterval(this.timer)
    this.isCounting = false
  }
  start = () => {
    this.stop()
    this.timeCount = 0
    this.isCounting = true
    this.timer = setInterval(function () {
      if (!this.isCounting) clearInterval(this.timer)
      this.timeCount++
    }.bind(this), 1)
  }
  format = (count): string => {
    return dayjs(count).format('mm:ss:SSS')
  }

至此,一个简单的计时器就做好了。

想起了高中时候,比着看谁停的离1秒最近。

完结散花

如发现文章内容有任何问题,请提出您的宝贵意见予以指正,感谢您的阅读。

HarmonyOS (鸿蒙操作系统) 提供了丰富的API和框架,你可以通过其服务、组件化的设计轻松创建自定义工具类,比如计时器。下面是一个简单的步骤和示例代码来展示如何在HarmonyOS中实现一个基础的计时器工具类: 1. **创建Service**: HarmonyOS强调微内核和服务化架构,你可以创建一个`TimerService`作为后台运行的服务,用于定时任务。 ```java import org.harmonyos.hal.system.IHwWallClock; import orgharmonyos.services.core.Service; public class TimerService extends Service { private IHwWallClock hwWallClock; // 使用硬件计时功能 @Override public void onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); hwWallClock = getSystem().getHalService(IHwWallClock.class); startTimer(); } private void startTimer() { long interval = intent.getLongExtra("interval", 0); // 获取用户设置的时间间隔 new Thread(() -> { while (!isStopped()) { try { Thread.sleep(interval); // 在这里添加你要执行的任务,例如回调或更新UI onTimerTick(); } catch (InterruptedException e) { Log.e(TAG, "Timer interrupted"); } } }).start(); } // 定义定时器触发的回调函数 protected void onTimerTick() { // ... 这里处理定时事件的具体逻辑 } // ... 其他service生命周期管理方法... } ``` 2. **提供公共API**: 可以通过暴露一些公共的静态方法给应用开发者使用,让他们可以启动和停止计时器。 ```java public static void start(int interval, Runnable task, Context context) { Intent serviceIntent = new Intent(context, TimerService.class); serviceIntent.putExtra("interval", interval); if (task != null) { serviceIntent.putExtra("timerTask", task); } context.startService(serviceIntent); } public static void stop(Context context) { Intent serviceIntent = new Intent(context, TimerService.class); context.stopService(serviceIntent); } ``` **注意事项**: - 在实际项目中,你需要处理异常情况,并确保在服务停止时清除定时任务。 - 使用HarmonyOS提供的`IHwWallClock`服务进行高精度计时,而不是`Thread.sleep()`,因为后者受线程调度影响可能不如硬件计时准确。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>