Logo

鸿蒙 Next 系统上体验开发一个精准的计时器应用

avatar jade 01 Aug 2024

download.png

鸿蒙 Next 系统简介

鸿蒙系统next是华为推出的一款全新操作系统,旨在打破传统操作系统的固有局限,舒缓软硬件之间的合作深度,使得不同类型的设备能够更好地实现连接与协同。鸿蒙系统next主要特点有以下几点:

  1. 分布式架构:支持多设备之间的无缝连接,实现设备之间的数据共享和协同操作。
  2. 轻量级内核:拥有精简高效的内核设计,提升系统运行效率,降低资源消耗。
  3. 智能化体验:提供智能识别和智能推荐等功能,为用户提供更加个性化、智能化的使用体验。
  4. 安全保障:采用多重安全策略和技术,确保用户数据的隐私和安全。
  5. 开放生态:鸿蒙系统next支持更多的开发者接入,丰富应用生态,为用户提供更多多样化的应用选择。

    总的来说,鸿蒙系统next是一款具有高度智能化、安全性和开放性的全新操作系统,将为用户带来更加便捷、高效的设备连接及体验。
    作为一名开发者,我最近在鸿蒙 Next 系统上开发了一个简单但实用的计时器应用。这个过程不仅让我深入了解了鸿蒙的开发生态,还让我体会到了ArkTS语言的强大之处。下面,我将分享这个计时器应用的开发过程和一些关键代码。

开发环境搭建

首先,我下载并安装了最新版的DevEco Studio。这是华为官方推荐的鸿蒙开发IDE,集成了所有必要的开发工具和模拟器。
download (1).png

项目创建

在DevEco Studio中,我创建了一个新的”Application”项目,选择ArkTS作为开发语言。ArkTS是基于TypeScript的声明式UI开发语言,语法直观,易于上手。

UI设计

对于计时器应用,我设计了一个简洁的界面,包括一个大型数字显示区、开始/暂停按钮和重置按钮。以下是主界面的部分代码:

typescript
Copy
@Entry
@Component
struct TimerPage {
    @State seconds: number = 0
    @State isRunning: boolean = false
    build() {
        Column() {
            Text(this.formatTime(this.seconds))
                .fontSize(60)
                .fontWeight(FontWeight.Bold)
                .margin({ bottom: 20 })
            Row() {
                Button(this.isRunning ? '暂停' : '开始')
                  .onClick(() => this.toggleTimer())
                Button('重置')
                  .onClick(() => this.resetTimer())
      }.width('100%').justifyContent(FlexAlign.SpaceAround)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
    .backgroundColor("#CCFFDD")
  }

  private formatTime(seconds: number): string {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  // ... 其他方法
}

计时器逻辑实现

typescript
Copy
import systemDateTime from'@ohos.systemDateTime';
@Component
struct TimerPage {
  // ... 其他代码
  privateintervalID: number = -1

  privatetoggleTimer() {
    if(this.isRunning) {
      clearInterval(this.intervalID)
    } else{
      conststartTime = systemDateTime.getTime()
      constinitialSeconds = this.seconds
      this.intervalID = setInterval(() => {
        constcurrentTime = systemDateTime.getTime()
        this.seconds = initialSeconds + Math.floor((currentTime - startTime) / 1000)
      }, 1000)
    }
    this.isRunning = !this.isRunning
  }
  privateresetTimer() {
    clearInterval(this.intervalID)
    this.seconds = 0
    this.isRunning = false
}
  // ... 其他方法
}

后台运行支持

为了让计时器在应用进入后台时仍能正常工作,我利用了鸿蒙的后台任务管理能力:

typescript
Copy
importbackgroundTaskManager from'@ohos.backgroundTaskManager'
@Component
struct TimerPage {
  // ... 其他代码
  aboutToDisappear() {
    if(this.isRunning) {
      letbgTask = backgroundTaskManager.requestBackgroundRunning({
        name: "TimerTask",
        description: "Keep timer running in background"
      })
      // 处理bgTask的结果
    }
  }
  // ... 其他方法
}

数据持久化

为了在应用重启后恢复计时状态,我使用了鸿蒙的数据管理服务:

typescript
Copy
import dataPreferences from '@ohos.data.preferences'
@Component
struct TimerPage {/
  / ... 其他代码
  async aboutToAppear() {
    let preferences = await dataPreferences.getPreferences(this.context, 'TimerPrefs')
    this.seconds = await preferences.get('seconds', 0) as number
    this.isRunning = await preferences.get('isRunning', false) as boolean
    if (this.isRunning) {
      this.toggleTimer()
    }
  }

  async onPageHide() {
    let preferences = await dataPreferences.getPreferences(this.context, 'TimerPrefs')
    await preferences.put('seconds', this.seconds)
    await preferences.put('isRunning', this.isRunning)
    await preferences.flush()
  }
  // ... 其他方法
}

运行截图

Screen Recording 2024-08-01 at 10.gif

性能优化

在开发过程中,我特别注意了应用的性能。使用ArkTS的声明式UI,渲染效率得到了很大提升。同时,我也确保了在不需要更新UI时不会触发不必要的重绘。

测试与调试

DevEco Studio提供了强大的模拟器和调试工具。我在不同尺寸的设备上进行了测试,确保应用在各种场景下都能正常工作。

总结

在鸿蒙 Next 系统上开发这个计时器应用是一次非常有趣的经历。ArkTS语言的声明式UI开发方式让界面构建变得简单直观。鸿蒙提供的系统API,如高精度时间测量、后台任务管理和数据持久化,让应用开发变得更加便捷。整个开发过程相对顺畅,鸿蒙的开发生态正在逐步完善,为开发者提供了一个充满潜力的新平台。

Tags
鸿蒙Next
应用开发
HarmonyOS