本节将介绍日志打印、时间换算等通用工具类的编写和使用,工具类可以简化应用代码编写和业务流程处理。
日志类
日志类Logger旨在提供一个全局的日志打印、日志管理的地方,既可以规范整个应用的日志打印,也方便日后对日志工具类进行修改,而不需要去改动代码中每一个调用日志的地方,如切换具体的日志实现类(比如不使用Console而是HiLog),将日志记录到本地文件等。
Logger对外的日志API全部使用静态方法,方便调用者使用,目前分verbose,debug,info,warn,error五个级别。
开发前请熟悉鸿蒙开发指导文档:[gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md
]
使用方法如下:
- import Logger日志类:
import { Logger } from '../utils/log/Logger';
- 调用对应级别的静态方法:
Logger.debug('MyAbilityStage', 'onCreate');
3、Logger类中包括debug、info、warn、error,具体内容如下:
// Logger.ets
import hilog from '@ohos.hilog';
const LOGGER_PREFIX: string = 'Healthy_life';
class Logger {
private domain: number;
private prefix: string;
...
constructor(prefix: string = '', domain: number = 0xFF00) {
this.prefix = prefix;
this.domain = domain;
}
debug(...args: string[]): void {
hilog.debug(this.domain, this.prefix, this.format, args);
}
info(...args: string[]): void {
hilog.info(this.domain, this.prefix, this.format, args);
}
warn(...args: string[]): void {
hilog.warn(this.domain, this.prefix, this.format, args);
}
error(...args: string[]): void {
hilog.error(this.domain, this.prefix, this.format, args);
}
}
export default new Logger(LOGGER_PREFIX, 0xFF02);
时间工具
为全局提供时间工具,避免重复定义。
- 常用时间相关常量:
// Utils.ets
const CHINESE_OF_WEEK: string[] = ['一', '二', '三', '四', '五', '六', '日'];
const YEAR: string = '年';
const MONTH: string = '月';
const DAY: string = '日';
const WEEK: string = '星期';
DAYS_OF_WEEK: number = 7;
const SUNDAY_FIRST_SHIFT: number = 6;
- 时间函数示例(由时间常量衍生出星期一到星期日和数字 1-7 的字典映射):
// Utils.ets
export const oneWeekDictFunc = () = > {
const oneWeekDict: Array< string > = [];
for (let index = 0;index < CHINESE_OF_WEEK.length; index++) {
oneWeekDict[index] = `${WEEK}${CHINESE_OF_WEEK[index]}`;
}
return oneWeekDict;
}
单位转换工具
把比例等分浮点数转换为百分比字符串。
例如成就页面,每一行平均分布三个徽章,可以先定义一个浮点数代表等分比例,再转换为百分比字符串。
// Utils.ets
export function ratio2percent(ratio: number): string {
return `${ratio * 100}%`;
}
使用方法如下:
- import 工具方法:
import { ratio2percent } from '../common/utils/Utils'
- 引用工具方法 ( 例如成就页面,每个徽章占据屏幕宽度的三分之一 ) :
// BadgeCardComponent.ets Column({space: commonConst.DEFAULT_18}) { ... // 省略徽章卡片的 UI 布局细节 } .width(ratio2percent(Const.ACHIEVE_SPLIT_RATIO)) // achieveConst.ACHIEVE_SPLIT_RATIO = 1 / 3
事件分发类
事件分发类提供应用全局的事件注册,分发,接受,可以实现组件之间的解耦。
事件分发类全局共享一个实例, 将事件处理统一管理(HealthDataSrcMgr是单例):
获取事件分发实例:
// HomeComponent.ets
@Provide broadCast: BroadCast = HealthDataSrcMgr.getInstance().getBroadCast();
// HealthDataSrcMgr.ets
public getBroadCast(): BroadCast {
return this.broadCast;
}
事件注册:
// CustomDialogView.ets
aboutToAppear() {
Logger.debug('CustomDialogView', 'aboutToAppear');
// 成就对话
this.broadCast.on(BroadCastType.SHOW_ACHIEVEMENT_DIALOG, (achievementLevel: number) = > {
Logger.debug('CustomDialogView', 'SHOW_ACHIEVEMENT_DIALOG');
this.achievementLevel = achievementLevel;
this.achievementDialog.open();
});
// 任务时钟对话框
this.broadCast.on(BroadCastType.SHOW_TASK_DETAIL_DIALOG,
(currentTask: TaskInfo, dialogCallBack: CustomDialogCallback) = > {
Logger.debug('CustomDialogView', 'SHOW_TASK_DETAIL_DIALOG');
this.currentTask = currentTask || TaskItem;
this.dialogCallBack = dialogCallBack;
this.taskDialog.open();
});
}
// BroadCast.ets
public on(event: string, callback: Function) {
Logger.info(FILE_TAG, 'register broadcast with type '+ event);
switch (event) {
case BroadCastType.SHOW_ACHIEVEMENT_DIALOG:
this.callBackArray.showAchievementDialog = callback;
break;
case BroadCastType.SHOW_TASK_DETAIL_DIALOG:
this.callBackArray.showTaskDetailDialog = callback;
break;
case BroadCastType.SHOW_TARGET_SETTING_DIALOG:
this.callBackArray.showTargetSettingDialog = callback;
break;
case BroadCastType.SHOW_REMIND_TIME_DIALOG:
this.callBackArray.showRemindTimeDialog = callback;
break;
case BroadCastType.SHOW_FREQUENCY_DIALOG:
this.callBackArray.showFrequencyDialog = callback;
break;
default:
break;
}
}
取消事件注册:
// TaskDetailComponent.ets
aboutToAppear() {
this.broadCast.off(BroadCastType.SHOW_TARGET_SETTING_DIALOG, () = > {});
this.broadCast.off(BroadCastType.SHOW_REMIND_TIME_DIALOG, () = > {});
this.broadCast.off(BroadCastType.SHOW_FREQUENCY_DIALOG, () = > {});
}
// BroadCast.ets
public off(event: string, callback: Function) {
if (event === null) {
Logger.info(FILE_TAG, 'cancel all broadcast');
this.callBackArray = callBackArrayTemp;
}
Logger.info(FILE_TAG, 'cancel broadcast with type '+ event);
const cbs = this.callBackArray;
if (!cbs) {
return;
}
if (callback === null) {
switch (event) {
case BroadCastType.SHOW_ACHIEVEMENT_DIALOG:
this.callBackArray.showAchievementDialog = () = > {};
break;
case BroadCastType.SHOW_TASK_DETAIL_DIALOG:
this.callBackArray.showTaskDetailDialog = () = > {};
break;
case BroadCastType.SHOW_TARGET_SETTING_DIALOG:
this.callBackArray.showTargetSettingDialog = () = > {};
break;
case BroadCastType.SHOW_REMIND_TIME_DIALOG:
this.callBackArray.showRemindTimeDialog = () = > {};
break;
case BroadCastType.SHOW_FREQUENCY_DIALOG:
this.callBackArray.showFrequencyDialog = () = > {};
break;
default:
break;
}
}
}
`HarmonyOS与OpenHarmony鸿蒙文档籽料:mau123789是v直接拿`
发送事件:
// HomeComponent.ets
taskItemAction(item: TaskInfo, isClick: boolean): void {
if (!this.homeStore.checkCurrentDay()) {
return;
}
if (isClick) {
// 点击时钟
let callback: CustomDialogCallback = { confirmCallback: (taskTemp: TaskInfo) = > {
this.onConfirm(taskTemp)
}, cancelCallback: () = > {
} };
this.broadCast.emit(BroadCastType.SHOW_TASK_DETAIL_DIALOG, [item, callback]);
} else {
// 编辑任务
let editTaskStr: string = JSON.stringify(TaskMapById[item.taskID - 1]);
let editTask: ITaskItem = JSON.parse(editTaskStr);
editTask.targetValue = item?.targetValue;
editTask.isAlarm = item.isAlarm;
editTask.startTime = item.startTime;
editTask.frequency = item.frequency;
editTask.isOpen = item.isOpen;
router.pushUrl({ url: 'pages/TaskEditPage', params: { params: JSON.stringify(editTask) } });
}
}
审核编辑 黄宇
-
鸿蒙
+关注
关注
57文章
2309浏览量
42740 -
HarmonyOS
+关注
关注
79文章
1967浏览量
30017 -
OpenHarmony
+关注
关注
25文章
3659浏览量
16151
发布评论请先 登录
相关推荐
评论