华为闹钟—HarmonyOS 鸿蒙Next基本完善
华为闹钟—HarmonyOS 鸿蒙Next基本完善
- Index
import { CanvasComp } from '../components/CanvasComp'
import { ClockItemComp } from '../components/ClockItemComp'
import { router } from '@kit.ArkUI'
import { ClockItem, ClockStore } from '../Utils/ClockStore'
@Entry
@Component
struct Index {
clockStore = new ClockStore()
//定义闹钟列表
@State
clockList:ClockItem[] = []
//从用户首选项中获取数据给闹钟赋值
async getData(){
const list = await this.clockStore.getAllClock()
this.clockList = list
}
//初次加载页面获取闹钟数据
aboutToAppear(): void {
this.getData()
}
//重新加载页面也要获取闹钟数据
onPageShow(): void {
this.getData()
}
build() {
Stack({ alignContent: Bottom }) {
Column({ space: 15 }) {
//闹钟
Text('闹钟')
.fontSize(24)
.width('100%')
//表盘
CanvasComp()
//闹钟管理
List({space:15}) {
ForEach(this.clockList, (item:ClockItem) => {
ListItem() {
ClockItemComp({item})
.onClick(()=>{
router.pushUrl({
url:'pages/DetailPage',
params:item
})
})
}
})
}
.height('45%')
}
.padding(15)
.height('100%')
.width('100%')
.backgroundColor('#F5F5F5')
//+
Text('+')
.onClick(()=>{
router.pushUrl({
url:'pages/DetailPage'
})
})
.backgroundColor('#06f')
.width(50)
.aspectRatio(1)
.fontSize(40)
.fontWeight(200)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.borderRadius(30)
.margin({ bottom: 50 })
}
}
}
- DetailPage
import { promptAction, router } from '@kit.ArkUI'
import { reminderAgentManager } from '@kit.BackgroundTasksKit'
import { ClockItem, ClockStore } from '../Utils/ClockStore'
import { util } from '@kit.ArkTS'
import { notificationManager } from '@kit.NotificationKit'
import { BusinessError } from '@kit.BasicServicesKit'
import { wantAgent } from '@kit.AbilityKit'
import { ReminderManager } from '../Utils/ReminderManager'
class date {
now: Date = new Date()
}
@Entry
@Component
struct DetailPage {
@State
state: date = { now: new Date() }
@State
clockItem: ClockItem = new ClockItem() //接收从主页传递过来的闹钟
//页面展示时从参数中获取值给 clockItem 赋值
aboutToAppear() {
const params = router.getParams() as ClockItem
this.clockItem = params
if (params) {
//给时间选择器也要设置值
this.state.now.setHours(this.clockItem.hour)
this.state.now.setMinutes(this.clockItem.minute)
}
}
//定义闹钟对象
clockStore = new ClockStore
async submit() {
//设置的小时
const hour = this.state.now.getHours()
//设置的分钟
const minute = this.state.now.getMinutes()
//添加后台闹铃提醒
const reminderRequest: reminderAgentManager.ReminderRequestAlarm = {
//设置闹铃提醒类型
reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM,
//设置提醒小时
hour,
//设置提醒分钟
minute,
//提醒的市场
ringDuration: 60,
title: '闹铃',
//跳转app
wantAgent:{
pkgName:"com.example.myclockproject",
abilityName:'EntryAbility'
},
//延迟或者关闭
actionButton:[{
title:'停止',
type:reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE//按钮类型为停止
},
{
title:'延迟10分钟提醒',
type:reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE//按钮类型为延迟提醒
}],
//设置延迟提醒的次数
snoozeTimes:2,
//设置延迟提醒的时间间隔 10分钟
timeInterval:10*60
}
//如果修改闹铃,那就把原来的提醒删除
// if (this.clockItem.reminderId) {
// reminderAgentManager.cancelReminder(this.clockItem.reminderId)
// }
// console.info('submit2')//
// let reminderId:number = 0//
// try {
// reminderId = await reminderAgentManager.publishReminder(reminderRequest)//
// }catch (e){
// console.info(`e:${JSON.stringify(e)}`)
// return
// }//
// console.info('submit2.1')//
//发布提醒 reminderId 注册提醒后赋值给reminderId
const reminderId = await ReminderManager.AddReminder(hour,minute)
//组织闹钟对象,讲数据存储到用户首选项中
await this.clockStore.addClockItem({
id: this.clockItem?this.clockItem.id:util.generateRandomUUID(), //随机生成id
hour,
minute,
enable: true,
reminderId
})
//提醒闹钟创建成功并返回主页
promptAction.showToast({ message:this.clockItem?'修改闹铃成功':'添加闹铃成功!' })
router.back()
}
//删除闹铃
remove(){
//删除用户首选项的该条闹铃
this.clockStore.delClock(this.clockItem.id)
//取消闹铃通知
reminderAgentManager.cancelReminder(this.clockItem.reminderId)
promptAction.showToast({message:'取消闹铃成功'})
//返回首页
router.back()
}
@Builder
CellBuilder(title: string, value: string) {
Row() {
Text(title)
Row() {
Text(value)
.fontColor('#999')
Image('/images/ic_public_arrow_right.svg')
.width(16)
.aspectRatio(1)
.fillColor('#999')
}
}
.padding({ left: 15, right: 15 })
.width('100%')
.height(64)
.justifyContent(FlexAlign.SpaceBetween)
.backgroundColor('#FFF')
}
build() {
Navigation() {
Column({space:20}) {
//1 时间组件
TimePicker({ selected: this.state.now })
.onChange(value => {
this.state.now.setHours(value.hour)
this.state.now.setMinutes(value.minute)
})
.width('100%')
.borderRadius(16)//根据边缘进行裁剪
.clip(true)
//2 闹铃名称和重复
Column({ space: 0.5 }) {
this.CellBuilder('闹铃名称', '闹铃')
this.CellBuilder('重复', '不重复')
}
.borderRadius(16)
.clip(true)
//3 删除闹铃
if (this.clockItem){
Text('删除闹铃')
.width(100)
.height(40)
.backgroundColor('#E3E4E5')
.fontColor('red')
.textAlign(TextAlign.Center)
.borderRadius(16)
.opacity(0.3) //蒙版
.onClick(()=>{
this.remove()
})
}
Button('允许通知')
.onClick(()=>{
let requestEnableNotificationCallback = (err: BusinessError): void => {
if (err) {
console.error(`requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info("requestEnableNotification success");
}
};
notificationManager.requestEnableNotification(requestEnableNotificationCallback);
})
}
.width('100%')
.height('100%')
.padding(15)
}
.title(this.clockItem?'修改闹铃':'新建闹钟')
.titleMode(NavigationTitleMode.Mini)
.mode(NavigationMode.Stack) //防止宽屏分成2栏
.menus([
{ value: '', icon: '/images/ic_confirm.png', action: () => this.submit() }
])
.backgroundColor('#F3F4F5')
}
}
- ClockStore
// 闹钟信息类定义
import { preferences } from '@kit.ArkData'
export class ClockItem {
id: string = '' //闹钟id
hour: number = 0 //小时
minute: number = 0 //分钟
enable: boolean = false //是否开启
reminderId: number = 0 //发布通知的id
}
//用户首选项工具
export class ClockStore {
//获取用户首选项
getStore() {
return preferences.getPreferences(getContext(this), 'clockStore')
}
//闹钟的添加
async addClockItem(clockItem: ClockItem) {
const store = await this.getStore()
//向首选项中存储数据,clockItem,key:id value:clockItem
await store.put(clockItem.id, JSON.stringify(clockItem))
store.flush()
}
//闹钟删除
async delClock(id: string) {
const store = await this.getStore()
await store.delete(id)
store.flush()
}
//获取闹钟列表,返回数组
async getAllClock() {
const store = await this.getStore()
const allDate: object = await store.getAll()
//allDate = {id1:clockItem jsonStr,id2:clockItem jsonStr}
const list = Object.keys(allDate).map<ClockItem>(key => JSON.parse(allDate[key]) as ClockItem)
return list
}
}
- ReminderManager
import { reminderAgentManager } from '@kit.BackgroundTasksKit'
export class ReminderManager {
static async AddReminder(hour: number, minute: number) {
//添加后台闹铃提醒
const reminderRequest: reminderAgentManager.ReminderRequestAlarm = {
//设置闹铃提醒类型
reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM,
//设置提醒小时
hour,
//设置提醒分钟
minute,
//提醒的市场
ringDuration: 60,
title: '闹铃',
//跳转app
wantAgent: {
pkgName: "com.example.myclockproject",
abilityName: 'EntryAbility'
},
//延迟或者关闭
actionButton: [{
title: '停止',
type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE//按钮类型为停止
},
{
title: '延迟10分钟提醒',
type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE//按钮类型为延迟提醒
}],
//设置延迟提醒的次数
snoozeTimes: 2,
//设置延迟提醒的时间间隔 10分钟
timeInterval: 10 * 60
}
//发布提醒 reminderId 注册提醒后赋值给reminderId
const reminderId = await reminderAgentManager.publishReminder(reminderRequest)
return reminderId
}
}
更多关于华为闹钟—HarmonyOS 鸿蒙Next基本完善的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
3 回复
华为闹钟在HarmonyOS鸿蒙Next系统中已经基本完善。该系统采用了分布式技术,能够在多设备之间实现无缝协同。闹钟功能不仅可以在手机上使用,还能在平板、智能手表等设备上同步设置和提醒。鸿蒙Next系统通过微内核架构提升了系统的稳定性和安全性,闹钟功能也因此更加可靠。此外,鸿蒙Next支持智能场景识别,能够根据用户的作息习惯自动调整闹钟设置,提供个性化的提醒服务。
华为的HarmonyOS鸿蒙Next系统在闹钟功能上已经基本完善,提供了多种个性化设置,如重复提醒、渐强铃声和智能跳过节假日等。用户可以根据需求自定义闹钟,确保准时起床。此外,系统还支持与其他设备的无缝联动,如通过智能音箱或手表进行提醒,提升了用户体验。整体来看,HarmonyOS的闹钟功能在稳定性和便捷性上表现出色,满足了日常使用需求。